I am trying to expose a c++ class to python using boost, and extract a object defined in python in c++ side.
What I have tried:
I defined my c++ class in the file MyInt.h:
<pre>
struct MyInt
{
int i_;
};
If I define the BOOST_PYTHON_MODULE in the project everything works fine. For example this code works well:
#include "MyInt.h"
BOOST_PYTHON_MODULE(Example)
{
bpy::class_<MyInt>("MyInt")
.def_readwrite("i_", &MyInt::i_);
}
int main()
{
PyImport_AppendInittab("Example", &PyInit_Example);
Py_Initialize();
try
{
bpy::object main_module = bpy::import("__main__");
bpy::object main_namespace = main_module.attr("__dict__");
main_namespace["ex"] = bpy::import("Example");
bpy::exec("i = ex.MyInt()", main_namespace, main_namespace);
bpy::exec("i.i_ = 5", main_namespace, main_namespace);
MyInt& myI = bpy::extract<MyInt&>(main_namespace["i"]);
std::cout << "MyI.i_ : " << myI.i_ << std::endl;
}
catch (bpy::error_already_set& pye)
{
PyErr_Print();
}
Py_Finalize();
system("Pause");
}
Now, if I build the Example.pyd file using the same BOOST_PYTHON_MODULE, i can import it in python but the following code in c++ doesn't work:
#include "MyInt.h"
int main()
{
HMODULE hLib = LoadLibrary("Example.pyd");
if (hLib)
{
typedef PyObject* (*PFN) ( void);
PFN init_func = (PFN)GetProcAddress(hLib,"PyInit_Example");
if (init_func != 0)
{
int y = 0;
if ((y = PyImport_AppendInittab("Example", init_func)) == -1)
{
std::cout << "PyImport failed" << std::endl;
}
}
}
Py_Initialize();
try
{
bpy::object main_module = bpy::import("__main__");
bpy::object main_namespace = main_module.attr("__dict__");
main_namespace["ex"] = bpy::import("Example");
bpy::exec("i = ex.MyInt()", main_namespace, main_namespace);
bpy::exec("i.i_ = 5", main_namespace, main_namespace);
MyInt& myI = bpy::extract<MyInt&>(main_namespace["i"]);
std::cout << "MyI.i_ : " << myI.i_ << std::endl;
}
catch (bpy::error_already_set& pye)
{
PyErr_Print();
}
Py_Finalize();
system("Pause");
if (hLib) FreeLibrary(hLib);
}
it seems that the load of library and the PyImport_AppendInitTab call is ok, but the following error is thrown:
TypeError: No registered converter was able to extract a C++ reference to type struct MyInt from this Python object of type MyInt
How can i fix this error?
Is it possible to register a converter from pyd file?
thanks