从Python调用C++64位共享库
Calling C++ 64bit shared library from Python
我想使用python 2.7.8.中给定的C++64位共享库(linux下的.so文件)中的一个函数
C++共享库的头具有以下功能:
EXPORT_CODE double CONVENTION PropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char *Ref);
我需要一个不需要修改共享库的C++代码的解决方案(已经存在一个带有自定义库的完整Python包装器)。
以下是基于以下答案的工作解决方案:
>>> import ctypes
>>> lib = ctypes.cdll.LoadLibrary("/PathTo/libCoolProp.so")
>>> PropsSI = lib.PropsSI
>>> PropsSI.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p, ctypes.c_double, ctypes.c_char_p)
>>> PropsSI.restype = ctypes.c_double
>>> result = PropsSI(b"H", b"T", 300., b"P", 101325., ctypes.create_string_buffer("Water", 8))
>>> result
112654.89965373254
这里有另一种写法:
>>> from ctypes import *
>>> CoolProp = cdll.LoadLibrary('/PathTo/libCoolProp.so')
>>> PropsSI = CoolProp.PropsSI
>>> PropsSI.restype = c_double
>>> print PropsSI(c_char_p("H"), c_char_p("T"),c_double(300.),c_char_p("P"),c_double(101325.),c_char_p("Water"))
112654.899654
ctypes
将为您执行大量类型强制。
例如,给定string.h
中定义的函数strchr
const char * strchr ( const char * str, int character );
您可以提供函数的参数类型和返回类型,而不必自己进行任何类型强制——ctypes
模块将为您处理此问题。唯一的例外是需要将char *
作为out(可变)参数传递。使用ctypes.create_string_buffer
创建此参数,并使用value
属性访问内容。
import ctypes
libc = ctypes.cdll.LoadLibrary("msvcrt")
# or on linux
# import ctypes.util
# libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
strchr = libc.strchr
strchr.argtypes = (ctypes.c_char_p, ctypes.c_char)
strchr.restype = ctypes.c_char_p
result = strchr(b"abcde", b"c")
assert result == b"cde"
请注意ctypes
如何自动将字符串参数转换为适当的类型,并能够将返回值转换回python字符串。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 在cuda线程之间共享大量常量数据
- 如何从具有移动语义的类对象中生成共享指针
- 在c代码之间共享数据的最佳方式
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 将静态库链接到不带-fPIC的共享库中
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 将应用程序从32位移植到64位时出现问题
- 使用Boost Interprocess创建托管共享内存需要很长时间
- 64位机器上的C++内存对齐
- 无法在Ubuntu上将共享库与Eclipse链接
- 从python调用openMP共享库时,未定义opnMP函数
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 如何从 c++ 代码生成 arm64-v8a 64 位共享对象?
- boost::OSX 上 32 位和 64 位程序之间共享内存中的进程间同步机制(互斥体、条件)
- 从Python调用C++64位共享库
- 在64位Ubuntu 12.04上运行aapt:加载共享库时出错:libc++.所以:没有这样的文件或目录
- boost::32位和64位进程之间的进程间共享内存
- 如何为C++代码制作64共享64位linux兼容库(*.so)