Skip to content

Instantly share code, notes, and snippets.

@sterin
Last active October 23, 2015 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sterin/63f661e46cbee6bafdff to your computer and use it in GitHub Desktop.
Save sterin/63f661e46cbee6bafdff to your computer and use it in GitHub Desktop.
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})
// 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;
}
#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;
}
#include <iostream>
#include "shared.h"
struct global
{
global()
{
std::cout << "global::global() : this = " << this << std::endl;
}
~global()
{
std::cout << "global::~global() : this = " << this << std::endl;
}
};
static global my_global;
void a_function_from_the_shared_library()
{
std::cout << "a_function_from_the_shared_library()" << std::endl;
}
#pragma once
void a_function_from_the_shared_library();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment