我试图用Python中的cType从DLL调用C++函数。我当前的问题是该函数似乎返回一个大整数,要么是正的,要么是负的,而不是我期望它返回的char指针。如果我把这个int转换成一个c_char_p并调用它的.value,它每次都会杀死我的内核。我在这个网站和文档里都找遍了,但还是搞不懂。我在这个网站上看到的很多东西甚至会给我带来错误,比如在ctypes对象和函数应该是字节对象或类似对象时,向它们传递字符串。下面是转换成dll的c++代码和我用来从dll调用函数的python代码。如果有人能帮我,那就太棒了。sayshomething是我们讨论的函数。谢谢。在
#pragma once
#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllexport)
#endif
#include <windows.h>
#include <cstring>
#ifdef __cplusplus
extern "C"
{
#endif
TESTLIBRARY_API char* SaySomething(const char* phrase);
#ifdef __cplusplus
};
#endif
import ctypes
dbl = ctypes.c_double
pChar = ctypes.c_char_p
pVoid = ctypes.c_void_p
libName = (r"D:\Documents\Coding Stuff\Visual Studio 2017\Projects\TestLibrary"
r"Solution\x64\Debug\TestLibrary.dll")
x = ctypes.windll.LoadLibrary(libName)
x.SaySomething.argtypes = [pChar]
x.SaySomething.restypes = pChar
phrase = b"Hi"
phrase = pChar(phrase)
res = x.SaySomething(phrase)
你现在可以做的是一个API泄漏。更好的解决方案是让Python为结果分配和管理内存。在
我还修复了注释中提到的
dllimport
,并在.cpp文件中定义了TESTLIBRARY_EXPORTS
,这样函数就可以从DLL中导出了。restype
也被修复了。在TesterLibrary.h
测试工具库.cpp
^{pr2}$tester2.py
输出
当不再有对
result
缓冲区的引用时,Python将自动释放它。在相关问题 更多 >
编程相关推荐