你现在可以做的是一个API泄漏。更好的解决方案是让Python为结果分配和管理内存。在
我还修复了注释中提到的dllimport,并在.cpp文件中定义了TESTLIBRARY_EXPORTS,这样函数就可以从DLL中导出了。restype也被修复了。在
TesterLibrary.h#pragma once
#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllimport)
#endif
#define WIN32_LEAN_AND_MEAN
#include
#ifdef __cplusplus
extern "C" {
#endif
TESTLIBRARY_API char* SaySomething(const char* phrase, char* result, size_t resultMaxLength);
#ifdef __cplusplus
}
#endif
测试工具库.cpp
^{pr2}$
tester2.pyimport ctypes
libName = (r"TestLibrary.dll")
x = ctypes.CDLL(libName)
x.SaySomething.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.c_size_t]
x.SaySomething.restype = ctypes.c_char_p
phrase = b"Hi"
result = ctypes.create_string_buffer(100)
res = x.SaySomething(phrase,result,ctypes.sizeof(result))
print(res)
print(result.value)
输出b'Decorated '
b'Decorated '
当不再有对result缓冲区的引用时,Python将自动释放它。在