How to pass ctypes.POINTER to boost.python

最后都变了- 提交于 2021-02-10 20:31:11

问题


I have following code:

old_lib.h:

struct DUMMY
{
    // some members
};

module.cpp:

#include <boost/python.hpp>
#include "old_lib.h"

namespace py = boost::python;

void foo(py::object const& p)
{
    // How to get rid of ctypes.addressof()?
    static py::object ctypes_addressof = py::import("ctypes").attr("addressof");
    DUMMY *ptr = *reinterpret_cast<DUMMY**>(uintptr_t(py::extract<uintptr_t>(ctypes_addressof(p))));
}

BOOST_PYTHON_MODULE(module)
{
    py::def("foo", &foo, args("p"));
}

old_python.py:

import ctypes
class DUMMY(ctypes.Structure):
    _pack_ = 4
PDUMMY = POINTER(DUMMY)
# some old stuff using PDUMMY

new_python.py:

from module import foo
from old_python import PDUMMY
x = PDUMMY()
# some calls to old python (e.g. initialization of x)
foo(x)

It's supposed that python code is unchangeable.

How to get rid of ctypes.addressof()? I guess, calling of it is more expensive than just extracting of value, especially in case of frequent calls of foo(). UPD: In other words, how to obtain a value of ctypes._Pointer instance without using ctypes.addressof()?

Is there a way to specify a type of argument as 'foo(PDUMMY p)' and write converter from ctypes.POINTER to PDUMMY?

来源:https://stackoverflow.com/questions/30220223/how-to-pass-ctypes-pointer-to-boost-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!