Last active
October 23, 2015 06:10
-
-
Save sterin/63f661e46cbee6bafdff to your computer and use it in GitHub Desktop.
A simple example for http://stackoverflow.com/questions/33258718/importing-python-extension-module-loading-already-loaded-shared-library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.0.0) | |
project(so_example) | |
# needed to link with Python | |
find_package(PythonLibs REQUIRED) | |
# a simple shared library | |
add_library(shared SHARED shared.cpp) | |
# a simple executable that links with the shared library and embeds Python | |
add_executable(main main.cpp) | |
target_link_libraries(main shared) | |
target_include_directories(main PRIVATE ${PYTHON_INCLUDE_DIRS}) | |
target_link_libraries(main ${PYTHON_LIBRARIES}) | |
# a simple Python extension that links with the shared library | |
python_add_module(extension SHARED extension.cpp) | |
target_link_libraries(extension shared) | |
target_include_directories(extension PUBLIC ${PYTHON_INCLUDE_DIRS}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a Python extension that is linked with the shared library | |
#include <iostream> | |
#include <Python.h> | |
#include "shared.h" | |
static PyObject *extension_error; | |
static struct PyModuleDef extension_module = { | |
PyModuleDef_HEAD_INIT, | |
"extension", | |
NULL, | |
-1, | |
NULL | |
}; | |
PyMODINIT_FUNC | |
PyInit_extension(void) | |
{ | |
std::cout << "PyInit_extension()" << std::endl; | |
a_function_from_the_shared_library(); | |
PyObject *m = PyModule_Create(&extension_module); | |
if (!m) | |
{ | |
return NULL; | |
} | |
return m; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <Python.h> | |
#include "shared.h" | |
using namespace std; | |
int main() | |
{ | |
cout << "main()" << endl; | |
a_function_from_the_shared_library(); | |
Py_InitializeEx(1); | |
PyEval_InitThreads(); | |
PyRun_SimpleString("print (\'Python\')"); | |
PyRun_SimpleString("import extension"); | |
Py_Finalize(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment