GDAL:获取底层C对象的指针/句柄
题
我有以下设置:
- GDAL库与Python绑定(SWIG)
- 一些胶合码(python)
- 一个c库,与ctypes接口
我想将Swig Feneracicetagcode对象的底层数据集指针/句柄传递给我的C库。如何检索此指针?
i do not 希望用swig接口c库。
解决方案
它实际上很容易,我希望我的解决方案是便携式的。给定,我的c函数定义看起来有点像:
int myfunc(GDALDatasetH ds);
.
然后我的ctypes
定义如下:
_lib = C.LibraryLoader(C.CDLL).LoadLibrary(lib_path)
_myfunc = _lib.myfunc
_myfunc.argtypes = [C.c_void_p]
_myfunc.restype = C.POINTER(C.c_char)
.
,我可以用:
调用c函数ds = gdal.Open(path)
...
_myfunc(C.c_void_p(long(ds.this)))
. 其他提示
我用CTYPES方法为此问题的方法是DS对象的参考计数不会自动递增,如果要超出范围,则会成为一个坏指针。
更好的方法是定义将管理数据参考计数器的C Python扩展模块。
我正在使用静态pyobject *来保持对象,显然一个真正的实现将更加智能地存储它。
static PyObject * ds;
PyObject* GiveDsToC(PyObject * self, PyObject * args)
{
PyObject * pThis=NULL;
unsigned long addr;
if(!PyArg_ParseTuple(args, "O", &ds))
return NULL;
/* Ensure the interpreter keeps ds around while we have it */
Py_INCREF(ds);
pThis = PyObject_GetAttrString(ds, "this"); // new reference
addr = PyLong_AsLong(pThis); // convert using __int__ method
Py_DECREF(pThis); // Release the object back
CallSomeCFunction(addr);
Py_RETURN_NONE;
}
void FinishedWithDS(void)
{
// Lock the GIL and decrement the reference counter
PyGILState_STATE state = PyGILState_Ensure();
Py_DECREF(ds);
PyGILState_Release(state);
}
. 不隶属于 StackOverflow