我想知道如何在SWIG中将成员函数包装为全局函数。
,
test.cpp
class test
{
public:
void foo1();
void foo2();
}
包装后,
test.py
class test:
def foo1():
...
def foo2():
...
如何写*。我的文件吗?
首先,您需要一个工作文件集。没有实现的类定义将无法工作:
test.hpp
class test {
public:
int foo1();
int foo2();
};
test.cpp
#include "test.hpp"
int test::foo1() { return 1; }
int test::foo2() { return 2; }
.i文件:
// Name of the module. For Python this must be the name of the final
// _test.pyd and test.py files after swig processing and compilation.
%module test
%{
// Code to be inserted in the generated wrapper code.
// The wrapper must be able to call the wrapped code so include the header.
#include "test.hpp"
%}
// This tells swig to wrap everything found in "test.cpp".
// Note it *does not* process #include in this file by default, just
// declaration found directly in the file.
%include "test.hpp"
运行SWIG生成(在本例中)test.py
和test_wrap.cxx
:
swig -python -c++ test.i
编译包装器。我直接跟MSVC谈。必须提供Python include和libs目录来构建Python扩展,最终的Python扩展名应该是_.pyd。
cl /EHsc /LD /W3 /Ic:python310include /Fe_test.pyd test_wrap.cxx test.cpp /link /libpath:c:python310libs
演示:
C:>swig -python -c++ test.i
C:>cl /nologo /EHsc /LD /W3 /Id:devpython310include /Fe_test.pyd test_wrap.cxx test.cpp /link /libpath:d:devpython310libs
test_wrap.cxx
test.cpp
Generating Code...
Creating library _test.lib and object _test.exp
C:>py
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.test()
>>> t.foo1()
1
>>> t.foo2()
2