Python swig - 从 ctypes 指针创建 swig 包装实例
Python swig - create swig wrapped instance from ctypes pointer
我有一个 class 用 swig 包装的 C++ 代码。我无法修改代码或包装。
在 python 中,我使用 ctypes 得到了一个指向所述 C++ class 实例的指针。
我如何围绕这个指针创建一个 swig 包装器?
我知道 swig 对象拥有一个 'this' 属性,该属性在内部指向包装对象,但我找不到将其设置为手头指针的方法。
感谢您的帮助!
你可以做到这一点,但这是相当多的工作,而且修复使 ctypes 或 SWIG 接口完整和可用的潜在问题会简单得多比力互换性。 (同样值得注意的是,从 SWIG 创建一个 ctypes 对象比做你想做的事情更容易,这是从一个 ctypes 创建一个 SWIG 对象)。
为了说明这一点,我创建了以下我们将用 SWIG 包装的头文件:
struct Foo {
double d;
char msg[20];
};
然后我用下面的接口包装了它:
%module test
%{
#include "test.h"
%}
// Prove I'm not cheating here - we can't even instantiate this class
%nodefaultctor;
%include "test.h"
我还添加了一个测试函数供我们从 ctypes 调用,它不是 SWIG 包装的:
#include "test.h"
// This function returns a Foo, but is only accessible to ctypes
extern "C" Foo *fun1() {
static Foo f = { 1.234, "Hello" };
return &f;
}
您对 SWIG 的这个 this
属性的猜测 classes 是一个很好的起点,但这并不像仅仅改变它那么简单 - 您插入的对象的类型必须符合 SWIG 的预期。它不仅仅是一个表示为 int 的指针:
repr(test.Foo().this) # You'll need to drop the nodefaultctor directive to see this
"<Swig Object of type 'Foo *' at 0x7f621197d1e0>"
如果我们检查 SWIG 生成的源代码,我们可以看到有一个函数接受一个指针、一些类型信息并为我们创建这些对象:
SWIGRUNTIME PyObject *
SwigPyObject_New(void *ptr, swig_type_info *ty, int own);
让我们暂时忽略 SWIGRUNTIME
默认定义为 static
的事实,为了让我们开始试验这个运行时,我们可以将它重新定义为 extern
。稍后我们将研究无法做到这一点的解决方法。
所以我们的目标是获取 "ctypes only" 函数的输出并将其传递,通过更多 ctypes 调用 SwigPyObject_New
来创建我们可以用 SWIG 的 this 属性交换的东西模块。
为了调用我们通常会调用 SWIG_TypeQuery
来查找要使用的正确 swig_type_info
。然而,这实际上是一个宏,它扩展为传递一些始终是静态的静态变量。所以我们将使用这个函数:
SWIGRUNTIME swig_type_info *
SWIG_Python_TypeQuery(const char *type)
(同SWIGRUNTIME
附带条件)。
至此,我们已经掌握了足够的知识,可以交换代理对象的 this 属性,如果我们能够构建捐赠者,就可以完成。 (尽管那会泄漏)。我们有两种方法可以使它变得更好:
test.Foo
内的猴子补丁 __init__
可以工作。如果您不想重新编译 SWIG 界面中确实有 %nodefaultctor
,这是最好的:
def patched_init(self, ptr):
self.this = ptr
test.Foo.__init__ = patched_init
创建一个只有 __init__
的新 class,它在修改 __class__
属性之前设置 this
属性,并改用它:
class FooCtypesSwigInterop(object):
def __init__(self, ptr):
self.this = ptr
self.__class__ = test.Foo
当您不想破坏 test.Foo
现有的 __init__
实现时,此选项最有意义。
话虽如此,我们现在可以通过以下方式实现最初的目标:
import ctypes
import test
# This *must* happen after the import of the real SWIG module
# 0x4 is RTLD_NOLOAD which ensures that we get the same handle as the Python
# import did, even if it was loaded with RTLD_LOCAL as Python is prone to.
swig_module = ctypes.PyDLL('./_test.so',ctypes.RTLD_LOCAL|0x4)
# Note that we used PyDLL instead of CDLL because we need to retain the GIL
# Setup SWIG_Python_TypeQuery to have the right argument/return types
# (Using void* as a substitute for swig_type_info*)
SWIG_Python_TypeQuery = swig_module.SWIG_Python_TypeQuery
SWIG_Python_TypeQuery.argtypes = [ctypes.c_char_p]
SWIG_Python_TypeQuery.restype = ctypes.c_void_p
# Likewise SwigPyObject_New, using ctypes.py_object though for return
SwigPyObject_New = swig_module.SwigPyObject_New
SwigPyObject_New.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
SwigPyObject_New.restype = ctypes.py_object
# Actually do the type query for the type our ctypes function returns:
SWIGTYPE_p_Foo = SWIG_Python_TypeQuery('Foo*')
print(hex(SWIGTYPE_p_Foo))
# Now the ctypes function itself that returns the type we want SWIG managed
fun1 = swig_module.fun1
fun1.argtypes = []
fun1.restype = ctypes.c_void_p
# Make the actual ctypes call we care about here
result = fun1()
print(hex(result))
# And then create a SwigPyObject for it from the void* return type
# Note that 0 means not owned by SWIG
sresult = SwigPyObject_New(result, SWIGTYPE_p_Foo, 0)
print(repr(sresult))
# This is how we jimmy it back into the this attribute of a SWIG type
class FooCtypesSwigInterop(object):
def __init__(self, ptr):
self.this = ptr
self.__class__ = test.Foo
c = FooCtypesSwigInterop(sresult)
# Finally a usable SWIG object from the ctypes call
print(c.msg)
这一切都编译并适用于:
swig3.0 -python -c++ -Wall test.i
g++ -shared -o _test.so test_wrap.cxx fun1.cc -Wall -Wextra -fPIC -I/usr/include/python2.7/ -std=c++11 -DSWIGRUNTIME=extern
LD_LIBRARY_PATH=. python run.py
并给我们:
0x7fb6eccf29e0
0x7fb6eccf2640
<Swig Object of type 'Foo *' at 0x7fb6ee436720>
Hello
要解决将 SWIGRUNTIME
定义为 static
的问题,您需要再执行一个步骤。使用调试符号或对您拥有但无法修改的 SWIG 二进制模块进行逆向工程以找到我们需要的两个函数的地址,这些函数未相对于导出的符号导出。然后您可以使用它们来构造 ctypes 函数指针,而不是通过名称查找它们。当然 buy/find/re-write SWIG 模块,或者将缺少的功能添加到 ctypes 接口可能会更容易。
(最后值得注意的是,如果 SWIG 与 -builtin
一起运行,它似乎不适用于此处,但需要进行一些实质性更改才能使此答案生效)。
我有一个 class 用 swig 包装的 C++ 代码。我无法修改代码或包装。 在 python 中,我使用 ctypes 得到了一个指向所述 C++ class 实例的指针。 我如何围绕这个指针创建一个 swig 包装器?
我知道 swig 对象拥有一个 'this' 属性,该属性在内部指向包装对象,但我找不到将其设置为手头指针的方法。
感谢您的帮助!
你可以做到这一点,但这是相当多的工作,而且修复使 ctypes 或 SWIG 接口完整和可用的潜在问题会简单得多比力互换性。 (同样值得注意的是,从 SWIG 创建一个 ctypes 对象比做你想做的事情更容易,这是从一个 ctypes 创建一个 SWIG 对象)。
为了说明这一点,我创建了以下我们将用 SWIG 包装的头文件:
struct Foo {
double d;
char msg[20];
};
然后我用下面的接口包装了它:
%module test
%{
#include "test.h"
%}
// Prove I'm not cheating here - we can't even instantiate this class
%nodefaultctor;
%include "test.h"
我还添加了一个测试函数供我们从 ctypes 调用,它不是 SWIG 包装的:
#include "test.h"
// This function returns a Foo, but is only accessible to ctypes
extern "C" Foo *fun1() {
static Foo f = { 1.234, "Hello" };
return &f;
}
您对 SWIG 的这个 this
属性的猜测 classes 是一个很好的起点,但这并不像仅仅改变它那么简单 - 您插入的对象的类型必须符合 SWIG 的预期。它不仅仅是一个表示为 int 的指针:
repr(test.Foo().this) # You'll need to drop the nodefaultctor directive to see this
"<Swig Object of type 'Foo *' at 0x7f621197d1e0>"
如果我们检查 SWIG 生成的源代码,我们可以看到有一个函数接受一个指针、一些类型信息并为我们创建这些对象:
SWIGRUNTIME PyObject *
SwigPyObject_New(void *ptr, swig_type_info *ty, int own);
让我们暂时忽略 SWIGRUNTIME
默认定义为 static
的事实,为了让我们开始试验这个运行时,我们可以将它重新定义为 extern
。稍后我们将研究无法做到这一点的解决方法。
所以我们的目标是获取 "ctypes only" 函数的输出并将其传递,通过更多 ctypes 调用 SwigPyObject_New
来创建我们可以用 SWIG 的 this 属性交换的东西模块。
为了调用我们通常会调用 SWIG_TypeQuery
来查找要使用的正确 swig_type_info
。然而,这实际上是一个宏,它扩展为传递一些始终是静态的静态变量。所以我们将使用这个函数:
SWIGRUNTIME swig_type_info *
SWIG_Python_TypeQuery(const char *type)
(同SWIGRUNTIME
附带条件)。
至此,我们已经掌握了足够的知识,可以交换代理对象的 this 属性,如果我们能够构建捐赠者,就可以完成。 (尽管那会泄漏)。我们有两种方法可以使它变得更好:
test.Foo
内的猴子补丁__init__
可以工作。如果您不想重新编译 SWIG 界面中确实有%nodefaultctor
,这是最好的:def patched_init(self, ptr): self.this = ptr test.Foo.__init__ = patched_init
创建一个只有
__init__
的新 class,它在修改__class__
属性之前设置this
属性,并改用它:class FooCtypesSwigInterop(object): def __init__(self, ptr): self.this = ptr self.__class__ = test.Foo
当您不想破坏
test.Foo
现有的__init__
实现时,此选项最有意义。
话虽如此,我们现在可以通过以下方式实现最初的目标:
import ctypes
import test
# This *must* happen after the import of the real SWIG module
# 0x4 is RTLD_NOLOAD which ensures that we get the same handle as the Python
# import did, even if it was loaded with RTLD_LOCAL as Python is prone to.
swig_module = ctypes.PyDLL('./_test.so',ctypes.RTLD_LOCAL|0x4)
# Note that we used PyDLL instead of CDLL because we need to retain the GIL
# Setup SWIG_Python_TypeQuery to have the right argument/return types
# (Using void* as a substitute for swig_type_info*)
SWIG_Python_TypeQuery = swig_module.SWIG_Python_TypeQuery
SWIG_Python_TypeQuery.argtypes = [ctypes.c_char_p]
SWIG_Python_TypeQuery.restype = ctypes.c_void_p
# Likewise SwigPyObject_New, using ctypes.py_object though for return
SwigPyObject_New = swig_module.SwigPyObject_New
SwigPyObject_New.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
SwigPyObject_New.restype = ctypes.py_object
# Actually do the type query for the type our ctypes function returns:
SWIGTYPE_p_Foo = SWIG_Python_TypeQuery('Foo*')
print(hex(SWIGTYPE_p_Foo))
# Now the ctypes function itself that returns the type we want SWIG managed
fun1 = swig_module.fun1
fun1.argtypes = []
fun1.restype = ctypes.c_void_p
# Make the actual ctypes call we care about here
result = fun1()
print(hex(result))
# And then create a SwigPyObject for it from the void* return type
# Note that 0 means not owned by SWIG
sresult = SwigPyObject_New(result, SWIGTYPE_p_Foo, 0)
print(repr(sresult))
# This is how we jimmy it back into the this attribute of a SWIG type
class FooCtypesSwigInterop(object):
def __init__(self, ptr):
self.this = ptr
self.__class__ = test.Foo
c = FooCtypesSwigInterop(sresult)
# Finally a usable SWIG object from the ctypes call
print(c.msg)
这一切都编译并适用于:
swig3.0 -python -c++ -Wall test.i
g++ -shared -o _test.so test_wrap.cxx fun1.cc -Wall -Wextra -fPIC -I/usr/include/python2.7/ -std=c++11 -DSWIGRUNTIME=extern
LD_LIBRARY_PATH=. python run.py
并给我们:
0x7fb6eccf29e0
0x7fb6eccf2640
<Swig Object of type 'Foo *' at 0x7fb6ee436720>
Hello
要解决将 SWIGRUNTIME
定义为 static
的问题,您需要再执行一个步骤。使用调试符号或对您拥有但无法修改的 SWIG 二进制模块进行逆向工程以找到我们需要的两个函数的地址,这些函数未相对于导出的符号导出。然后您可以使用它们来构造 ctypes 函数指针,而不是通过名称查找它们。当然 buy/find/re-write SWIG 模块,或者将缺少的功能添加到 ctypes 接口可能会更容易。
(最后值得注意的是,如果 SWIG 与 -builtin
一起运行,它似乎不适用于此处,但需要进行一些实质性更改才能使此答案生效)。