2016-06-03 4 views
5

내 C++ 프로그램에 파이썬을 임베드했습니다.PyImport_ImportModule, 메모리에서 모듈을로드 할 수 있습니까?

PyImport_ImportModule을 사용하여 .py 파일로 작성된 모듈을로드합니다. 그러나 메모리에서 어떻게로드 할 수 있습니까? 내 .py 파일이 암호화되어 있다고 가정 해 봅시다. 먼저 암호를 해독하고 코드를 파이썬에 제공하여 실행해야합니다.

또한 가져 오기 메커니즘을 무시하거나 가로 채거나 수정할 수 있다면 좋겠지 만 파일 시스템에서 모듈을로드하지는 않지만 내 메모리 블록은 어떻게 수행 할 수 있습니까?

답변

6

다음의 예는 C 문자열에서 모듈을 정의하는 방법을 보여줍니다

#include <stdio.h> 
#include <Python.h> 
int main(int argc, char *argv[]) 
{ 
    Py_Initialize(); 
    PyRun_SimpleString("print('hello from python')"); 

    // fake module 
    char *source = "__version__ = '2.0'"; 
    char *filename = "test_module.py"; 

    // perform module load 
    PyObject *builtins = PyEval_GetBuiltins(); 
    PyObject *compile = PyDict_GetItemString(builtins, "compile"); 
    PyObject *code = PyObject_CallFunction(compile, "sss", source, filename, "exec"); 
    PyObject *module = PyImport_ExecCodeModule("test_module", code); 

    PyRun_SimpleString("import test_module; print(test_module.__version__)"); 

    Py_Finalize(); 
    return 0; 
} 

출력 :

hello from python 
version: 2.0 

당신에 대한 import hooks 워드 프로세서를 읽을 수 있습니다. find_moduleload_module 메소드를 사용하여 클래스를 정의해야합니다. 다음과 같은 것이 작동해야합니다.

PyObject* find_module(PyObject* self, PyObject* args) { 
    // ... lookup args in available special modules ... 
    return Py_BuildValue("B", found); 
} 

PyObject* load_module(PyObject* self, PyObject* args) { 
    // ... convert args into filname, source ... 
    PyObject *builtins = PyEval_GetBuiltins(); 
    PyObject *compile = PyDict_GetItemString(builtins, "compile"); 
    PyObject *code = PyObject_CallFunction(compile, "sss", source, filename, "exec"); 
    PyObject *module = PyImport_ExecCodeModule("test_module", code); 
    return Py_BuildValue("O", module); 
} 

static struct PyMethodDef methods[] = { 
    { "find_module", find_module, METH_VARARGS, "Returns module_loader if this is an encrypted module"}, 
    { "load_module", load_module, METH_VARARGS, "Load an encrypted module" }, 
    { NULL, NULL, 0, NULL } 
}; 

static struct PyModuleDef modDef = { 
    PyModuleDef_HEAD_INIT, "embedded", NULL, -1, methods, 
    NULL, NULL, NULL, NULL 
}; 

static PyObject* PyInit_embedded(void) 
{ 
    return PyModule_Create(&modDef); 
} 

int main() { 
    ... 
    PyImport_AppendInittab("embedded", &PyInit_embedded); 
    PyRun_SimpleString("\ 
import embedded, sys\n\ 
class Importer:\n\ 
    def find_module(self, fullpath):\n\ 
     return self if embedded.find_module(fullpath) else None\n\ 
    def load_module(self, fullpath):\n\ 
     return embedded.load_module(fullpath)\n\ 
sys.path_hooks.insert(0, Importer())\n\ 
"); 
    ... 
} 
+0

감사합니다! 첫 번째 예제는 완벽하게 작동합니다! – kchkg

관련 문제