您构建 C 代码的方式看起来更接近于一个扩展模块 ([Python 3]: Extending Python with C or C++),而不是一个简单的.dll。检查 [SO]: Pass str as an int array to a Python C extended function (extended using SWIG) (@CristiFati's answer) 以获取方法之间的比较。
然后,作为注释,您需要为导入的函数指定 argtypes 和 restype(这正是您获得 int)。检查[SO]: Python ctypes cdll.LoadLibrary, instantiate an object, execute its method, private variable address truncated,如果不这样做会发生什么。
还列出了[Python 3]: ctypes - A foreign function library for Python 页面。
关于代码的几点说明:
所以,假设你有一个工作的 .dll,你会如何使用它(盲目地发布代码):
mylib = ctypes.pydll.LoadLibrary('./mylib.so')
outvar = ctypes.py_object.in_dll(mylib, "outvar") # Note that you might have to declare it as extern "C", so its name doesn't get mangled
@EDIT0:
我创建了一个虚拟示例来测试一切是否正常。
dll.c:
#include <Python.h>
#if defined(_WIN32)
# define EXPORT __declspec(dllexport)
#else
# define EXPORT
#endif
EXPORT PyObject *tp = NULL;
EXPORT int i = 123;
EXPORT char *s = "Gainarie";
EXPORT float f = -3.14;
EXPORT void initTpl() {
tp = PyTuple_New(2);
PyTuple_SET_ITEM(tp, 0, PyLong_FromLong(7));
PyTuple_SET_ITEM(tp, 1, PyLong_FromLong(-9));
}
code.py:
#!/usr/bin/env python3
import sys
import ctypes
def main():
dll = ctypes.PyDLL("./dll.so")
i = ctypes.c_int.in_dll(dll, "i")
s = ctypes.c_char_p.in_dll(dll, "s")
f = ctypes.c_float.in_dll(dll, "f")
dll.initTpl()
tp = ctypes.py_object.in_dll(dll, "tp")
print(i.value, s.value, f.value, tp.value, type(tp.value))
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
注意事项:
- 我只在 Win 上进行了测试,因为我没有在我的 Lnx VM 上传输我的文件,但这不应该是问题
- 由于它仅用于演示目的,我并不关心 内存泄漏(我也没有检查是否需要 Py_XDECREF)
输出:
e:\Work\Dev\StackOverflow\q054429301>dir /b
code.py
dll.c
e:\Work\Dev\StackOverflow\q054429301>"c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x64
e:\Work\Dev\StackOverflow\q054429301>cl /nologo /DDLL /MD /I"c:\Install\x64\Python\Python\03.06.08\include" dll.c /link /NOLOGO /DLL /LIBPATH:"c:\Install\x64\Python\Python\03.06.08\libs" /OUT:dll.so
dll.c
Creating library dll.lib and object dll.exp
e:\Work\Dev\StackOverflow\q054429301>dir /b
code.py
dll.c
dll.exp
dll.lib
dll.obj
dll.so
e:\Work\Dev\StackOverflow\q054429301>"e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
123 b'Gainarie' -3.140000104904175 (7, -9) <class 'tuple'>