我有一個包含對象(例如STL容器)的C/C++結構。我想使用ctypes從Python訪問此結構。例如,如何在Python ctypes中包含包含C++對象的C結構
C/C++:
struct Foo {
int bar;
vector<int> baz;
double quxx;
}
的Python的ctypes:
from ctypes import *
class Foo(Structure):
_fields_ = [
("bar", c_int),
("baz", ???), <--- what do i put here?
("quxx", c_double),]
我意識到使用ctypes的,而無需創建包裝函數的STL容器我無法訪問,但它會是不錯能夠訪問「bar」和「quxx」。我能做到這一點的唯一方法是隻處理不透明的指針和包裝函數,例如
C/C++:
int Foo_bar(*Foo foo) { return foo->bar; }
...
的Python
class Foo_p(c_void_p): pass
my_Foo_p = ... somehow get a Foo pointer ...
bar = mylib.Foo_bar(my_Foo_p)
這似乎笨拙。有沒有辦法爲包含C++對象的C結構創建ctypes.Structure?也許使用sizeof?
爲什麼你需要那個?無論如何,如果包含的C++對象具有不平凡的構造函數或析構函數,您將無法以任何可靠的方式使用Foo對象。 – filmor 2014-10-08 07:47:22
我知道從Python構建和銷燬這樣的對象是不可能的,但我想要做的就是訪問它的基本C類型的成員。 – user3533069 2014-10-08 16:24:34