此问题紧跟this one。
我使用CFFI创建DLL,并从C ++应用程序中调用它。我在问自己,以了解如何释放由DLL分配的内存,并遵循its answer中@metal的想法。
这是我的Python代码:
import cffi
ffibuilder = cffi.FFI()
ffibuilder.embedding_api('''
char* get_string();
void free_char(char*);
''')
ffibuilder.set_source('my_plugin', '')
ffibuilder.embedding_init_code('''
from my_plugin import ffi, lib
@ffi.def_extern()
def get_string():
val = "string"
return lib.strdup(val.encode())
@ffi.def_extern()
def free_char(ptr):
lib.free(ptr)
''')
ffibuilder.cdef('''
char *strdup(const char *);
void free(void *ptr);
''')
ffibuilder.compile(target='my-plugin.*', verbose=True)
还有我的C ++代码:
#include <iostream>
#include <windows.h>
typedef char* (__stdcall *get_string_t)();
typedef void (__stdcall *free_char_t)(char*);
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary("my-plugin.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return -1;
}
get_string_t get_string = (get_string_t)GetProcAddress(hGetProcIDDLL, "get_string");
if (!get_string) {
std::cout << "could not locate the function" << std::endl;
return -1;
}
free_char_t free_char = (free_char_t)GetProcAddress(hGetProcIDDLL, "free_char");
if (!free_char) {
std::cout << "could not locate the function" << std::endl;
return -1;
}
for(int i = 0; i < 25000000; i++)
{
char* val = NULL;
val = get_string();
if(i % 10000 == 0)
{
std::cout << "Value " << i << " = " << val << std::endl;
}
if(val)
free_char(val);
}
std::cout << "End" << std::endl;
return 0;
}
我得到这个结果:
Value 0 = string
Value 10000 = string
Value 20000 = string
Value 30000 = string
Value 40000 = string
Value 50000 = string
Value 60000 = string
Value 70000 = string
Value 80000 = string
Value 90000 = string
Value 100000 = string
Value 110000 = string
Value 120000 = string
Value 130000 = string
Value 140000 = string
Value 150000 = string
Value 160000 = string
Value 170000 = string
Value 180000 = string
Value 190000 = string
Value 200000 = string
Value 210000 = string
Value 220000 = string
Value 230000 = string
Value 240000 = string
Value 250000 = string
From cffi callback <function get_string at 0x03470810>:
MemoryError: Stack overflow
From cffi callback <function get_string at 0x03470810>:
From cffi callback <function get_string at 0x03470810>:
From cffi callback <function get_string at 0x03470810>:
From cffi callback <function get_string at 0x03470810>:
此错误是什么意思?我没有内存问题,因为我使用新的free_char
函数释放了内存。顺便说一句,如果我取消对free_char
的调用,我可以进行所有循环(但是内存不会释放)。
答案 0 :(得分:1)
摘自cffi的文档:
推荐的与Python 2.7兼容的C编译器是这样的:
http://www.microsoft.com/en-us/download/details.aspx?id=44266
...
对于Python 3.4及更高版本:
https://www.visualstudio.com/en-us/downloads/visual-studio-2015-ctp-vs
然后,您应该降级python或升级visual-studio。