swig、python和wchar\t问题

2024-09-21 01:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是pythoncbindingswig的新手,已经尝试解决这个问题一段时间了。我有一个外部C库(Example.C),我想从Python调用它。我阅读了Swig教程,能够在很短的时间内生成包装器。现在的问题是,当我调用API并得到以下信息时:

>>> import Example
>>> dir(Example)
['Example_CreateConnection', 'trimmed to fit the screen']
>>> Example.Example_CreateConnection("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: in method 'Example_CreateConnection', argument 1 of type 'ExampleChar const *'

似乎找不到类型ExampleChar。以下是我的swig文件:

^{pr2}$

ExampleTypes.h如下所示:

#ifndef ExampleTypes_H
#define ExampleTypes_H

typedef wchar_t ExampleChar;

#endif /* ExampleTypes_H */

示例sdk.h如下所示:

#ifndef ExampleSDK_H
#define ExampleSDK_H

#include "ExampleTypes.h"
void Example_CreateConnection(const ExampleChar *temp);

#endif /* ExampleSDK_H */

以下是用于生成包装器的命令行:

swig -python -I. Example.i
gcc -c Example.c -I/Developer/SDKs/MacOSX10.6.sdk/usr/include/
gcc -c Example_wrap.c -I/usr/include/python2.6 -I.
gcc -bundle -flat_namespace -undefined suppress -o _Example.so Example_wrap.o Example.o -L/usr/lib/python2.6/config/ -lpython2.6

下面是Example.c的外观:

#include "runetype.h" // for Mac wchar_t definition

#include "ExampleSDK.h"

void Example_CreateConnection(const ExampleChar *temp)
{
    //do nothing
}

我不知道它有什么毛病。我希望有人能指出我在这里犯的错误。谢谢您。在

谨致问候

川林


Tags: inincludeexampleusrswiggccendifconst
1条回答
网友
1楼 · 发布于 2024-09-21 01:16:46

上次我将wchat_t与SWIG+Python一起使用时,我最终需要添加如下内容:

%include "pywstrings.swg"
%include "pystrings.swg"
%include "std_string.i"
%include "typemaps.i"  

%fragment("SWIG_AsVal_wchar_t", "header", fragment="<wchar.h>") {
    SWIGINTERN int SWIG_AsVal_wchar_t(PyObject* p, wchar_t* c) {
        return SWIG_OK;
    }
}
%fragment("SWIG_From_wchar_t", "header", fragment="<wchar.h>") {
    SWIGINTERNINLINE PyObject* SWIG_From_wchar_t(wchar_t c) {
        return SWIG_Py_Void();
    }
} 

// Python -> C
%typemap(in) wchar_t const * {
  $1 = PyString_to_wchar_t($input);
}

// C -> Python
%typemap(out) wchar_t * {
  $result = wchar_t_to_PyObject($1);
}

在我的Swig接口文件中。在

相关问题 更多 >

    热门问题