ctypes
适用于 C,但您可以编写一个包装器来公开 C++ 类。既然你提到你使用 Python 3.1,我还注意到你有一个 Unicode 字符串c_char_p('c1')
在哪里。'c1'
由于提供的示例不是一个完整的示例,无法按原样重现问题,因此很难判断您遇到了什么问题。
下面是一个完整的工作示例。您可以通过运行“nmake”从 Visual Studio 命令提示符构建它。
lib1.cpp
这个包装器将 C++ 对象“扁平化”为 C API。
#include "lib2.h"
extern "C" {
__declspec(dllexport) lib2* lib2_new() { return new lib2; }
__declspec(dllexport) void lib2_delete(lib2* p) { delete p; }
__declspec(dllexport) void lib2_func(lib2* p, char* c1, char* c2, double d) {
p->func(c1,c2,d);
}
}
lib2.h
#ifdef LIB2_EXPORTS
# define LIB2_API __declspec(dllexport)
#else
# define LIB2_API __declspec(dllimport)
#endif
class LIB2_API lib2
{
public:
void func(char * c1, char * c2, double d);
};
lib2.cpp
#include <stdio.h>
#include "lib2.h"
void lib2::func(char * c1, char * c2, double d)
{
printf("%s %s %f\n",c1,c2,d);
}
生成文件
all: lib1.dll lib2.dll
lib1.dll: lib1.cpp lib2.dll
cl /nologo /LD /W4 lib1.cpp -link lib2.lib
lib2.dll: lib2.cpp lib2.h
cl /nologo /LD /W4 /D LIB2_EXPORTS lib2.cpp
测试.py
#!python3
from ctypes import *
class lib2:
lib1 = CDLL('lib1')
# It's best to declare all arguments and types, so Python can typecheck.
lib1.lib2_new.argtypes = []
lib1.lib2_new.restype = c_void_p # Can use this for an opaque pointer.
lib1.lib2_func.argtypes = [c_void_p,c_char_p,c_char_p,c_double]
lib1.lib2_func.restype = None
lib1.lib2_delete.argtypes = [c_void_p]
lib1.lib2_delete.restype = None
def __init__(self):
self.obj = self.lib1.lib2_new()
def __del__(self):
self.lib1.lib2_delete(self.obj)
def func(self,c1,c2,d):
self.lib1.lib2_func(self.obj,c1,c2,d)
o = lib2()
o.func(b'abc',b'123',1.2) # Note byte strings
输出
C:\temp>nmake
Microsoft (R) Program Maintenance Utility Version 11.00.50727.1
Copyright (C) Microsoft Corporation. All rights reserved.
cl /nologo /LD /W4 /D LIB2_EXPORTS lib2.cpp
lib2.cpp
Creating library lib2.lib and object lib2.exp
cl /nologo /LD /W4 lib1.cpp -link lib2.lib
lib1.cpp
Creating library lib1.lib and object lib1.exp
C:\temp>test.py
abc 123 1.200000
备择方案
由于编写包装器可能很乏味,因此最好使用boost::Python
,Cython
或SWIG
. 我最熟悉 SWIG,所以这里有另一个例子:
生成文件
all: _lib2.pyd lib2.dll
PYTHON_ROOT = c:\python33
lib2_wrap.cxx: lib2.i
@echo Generating wrapper...
swig -c++ -python lib2.i
_lib2.pyd: lib2_wrap.cxx lib2.dll
cl /nologo /EHsc /MD /LD /W4 /I$(PYTHON_ROOT)\include lib2_wrap.cxx -link lib2.lib /LIBPATH:$(PYTHON_ROOT)\libs /OUT:_lib2.pyd
lib2.dll: lib2.cpp lib2.h
cl /nologo /LD /W4 /D LIB2_EXPORTS lib2.cpp
lib2.i
%module lib2
%begin %{
#pragma warning(disable:4127 4211 4706)
%}
%{
#include "lib2.h"
%}
%include <windows.i>
%include "lib2.h"
测试.py
#!python3
import lib2
o = lib2.lib2()
o.func('abc','123',1.2) #Note SWIG encodes Unicode strings by default
输出
C:\temp>nmake /las
Generating wrapper...
lib2.cpp
Creating library lib2.lib and object lib2.exp
lib2_wrap.cxx
Creating library lib2_wrap.lib and object lib2_wrap.exp
C:\temp>test
abc 123 1.200000