Python から CPP の呼出し
雰囲気はつかめてきたので,以前作成した cpp を呼んでみることに…
実際の処理部分は C++ のコードだが,呼び出しは C の関数.
また引数もない状態なので,C 関数の system(“a.out”) と呼んでいるのと同様.
#include "i_rd_dbg.hxx" int _tmain(int argc, TCHAR* argv[]) { ::Test_Revise_deg() ; return 0 ; }
#include <Python.h> #include "i_rd_dbg.hxx" #include "messbar.cxx" static PyObject* call_cpp(PyObject* self, PyObject* args) { ::Test_Revise_deg() ; return Py_None ; } static PyMethodDef myMethods[] = { { "_call_cpp_", call_cpp, METH_NOARGS, "call cpp" }, { NULL }, } ; static struct PyModuleDef call_mod = { PyModuleDef_HEAD_INIT, "call_mod", "call_cpp module", -1, myMethods } ; PyMODINIT_FUNC PyInit_call_mod(void) { return PyModule_Create(&call_mod) ; }
コンパイルして import まではできたが,メソッドをうまく呼び出せない.
>>> call_mod.call_cpp()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module ‘call_mod’ has no attribute ‘call_cpp’
>>>
それで,メソッドを表示できないかと思い検索すると,
python でメソッドの一覧を取得する方法
他に dir(call_mod) もあった.
Iwao@AS5202T:/volume1/home/Iwao/test/test_py/call_c/call_cpp/T_Rvs_sc $ g++ rvs_sc_w.cpp -o call_mod.so -fPIC -Wall -shared -I /volume1/.@plugins/AppCentral/python3/include/python3.7m/ Iwao@AS5202T:/volume1/home/Iwao/test/test_py/call_c/call_cpp/T_Rvs_sc $ Iwao@AS5202T:/volume1/home/Iwao/test/test_py/call_c/call_cpp/T_Rvs_sc $ python3 Python 3.7.0 (default, Aug 23 2018, 17:48:39) [GCC 4.6.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import call_mod >>> call_mod.call_cpp Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'call_mod' has no attribute 'call_cpp' >>> call_mod.call_cpp() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'call_mod' has no attribute 'call_cpp' >>> obj = call_mod >>> import inspect >>> for m in inspect.getmembers(obj): ... print(m) ... ('__doc__', 'call_cpp module') ('__file__', '/volume1/home/Iwao/test/test_py/call_c/call_cpp/T_Rvs_sc/call_mod.so') ('__loader__', <_frozen_importlib_external.ExtensionFileLoader object at 0x7f5a1a35ec50>) ('__name__', 'call_mod') ('__package__', '') ('__spec__', ModuleSpec(name='call_mod', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x7f5a1a35ec50>, origin='/volume1/home/Iwao/test/test_py/call_c/call_cpp/T_Rvs_sc/call_mod.so')) ('_call_cpp_', <built-in function _call_cpp_>) >>> call_mod._call_cpp_() >>>