我想在Python中使用C ++函数:
struct DataWrap
{
wchar_t* data;
int size;
}
extern int fun1( const char* szInBuffer, unsigned int inSize,DataWrap* buff);
fun1
获取char
中szInBuffer
的数组,其大小为inSize
,并在dataWrap->data
中返回新分配的UTF-16字符串
我想在Python中使用这个函数fun1
。
%typemap(argout) DataWrap* buff{
int byteorder = -1;
$input = PyUnicode_DecodeUTF16( (const char*)($1->data), ($1->size)*sizeof(wchar_t) , NULL, &byteorder);
}
这确实有效,但这里有内存泄漏
因为dataWrap->data
分配的fun1
永远不会被释放。
我试图解决这个问题:
%typemap(argout) DataWrap* buff{
int byteorder = -1;
$input = PyUnicode_DecodeUTF16( (const char*)($1->data), ($1->size)*sizeof(wchar_t) , NULL, &byteorder);
delete $1;
}
现在代码崩溃了。
我做错了什么?这是正确的为什么要使用SWIG才能将UTF-16字符串输入Python?
答案 0 :(得分:2)
试试freearg
typemap:
%typemap(freearg) DataWrap *buff {
delete $1->data;
}
另外,你有delete $1;
。它应该是delete $1->data
吗?
修改强>
在玩这个可能与您的问题相关的问题时,我发现了另一个问题。如果您在Windows上并且fun1
的实现与SWIG包装器代码位于不同的DLL中,请确保使两个DLL链接到相同的C运行时DLL(通过Microsoft中的/MD
编译器开关例如VC ++,因为内存将在一个DLL中被分配(假设new
)并在另一个DLL中被释放。
这是我正在玩的代码。它可能会帮助你。它还包括一个类型图,用于消除从Python发送字符串和大小,以及一个类型映射,以生成临时的DataWrap对象,因此它也不必传递。在实现文件x.cpp
中,我伪造了一个将字符串转换为UTF16的实现,该实现仅适用于简单的ASCII字符串,以便处理。
另请注意,我在不使用freearg
类型地图的情况下开始工作,尽管使用类型地图也适用于我。
_x.pyd: x_wrap.cxx x.dll
cl /MD /nologo /LD /Zi /EHsc /W4 x_wrap.cxx /Id:\dev\python27\include -link /LIBPATH:d:\dev\python27\libs /OUT:_x.pyd x.lib
x.dll: x.cpp x.h
cl /MD /nologo /Zi /LD /EHsc /W4 x.cpp
x_wrap.cxx: x.h x.i
swig -python -c++ x.i
%module x
%begin %{
#pragma warning(disable:4127 4211 4706)
%}
%{
#include "x.h"
%}
%include <windows.i>
%typemap(in) (const char *szInBuffer,unsigned int inSize) {
if (!PyString_Check($input)) {
PyErr_SetString(PyExc_ValueError, "Expecting a string");
return NULL;
}
$1 = PyString_AsString($input);
$2 = PyString_Size($input);
}
%typemap(in, numinputs=0) DataWrap* buff (DataWrap temp) {
$1 = &temp;
}
%typemap(argout) DataWrap* buff {
int byteorder = -1;
$result = PyUnicode_DecodeUTF16((const char*)($1->data), ($1->size)*sizeof(wchar_t), NULL, &byteorder);
delete [] $1->data;
}
%include "x.h"
#ifdef API_EXPORTS
# define API __declspec(dllexport)
#else
# define API __declspec(dllimport)
#endif
struct DataWrap
{
wchar_t* data;
int size;
};
extern "C" API void fun1(const char* szInBuffer, unsigned int inSize, DataWrap* buff);
#include <stdlib.h>
#define API_EXPORTS
#include "x.h"
API void fun1(const char* szInBuffer, unsigned int inSize, DataWrap* buff)
{
unsigned int i;
buff->size = inSize;
buff->data = new wchar_t[inSize];
for(i = 0; i < inSize; i++)
buff->data[i] = szInBuffer[i];
}
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import x
>>> x.fun1('abc')
u'abc'