나는 이런 종류의 일을 위해 Cython을 사용할 것을 권장합니다. another question의 예가 수정되었습니다. (편집가 : 요청에 따라, 나는 C++ 클래스를 랩하는 확장 된 예제를 추가, 더 아래를 참조하십시오.)
편집 : 간단한 예를 들어, 하나의 방법 (C++ -> 파이썬).
quacker.py :
def quack():
print("Quack!")
cquacker.pyx :
from quacker import quack
cdef public void cquack():
quack()
MAIN.CPP :
#if _WIN32
#include <direct.h>
#define getcwd _getcwd
#define PATH_SEPARATOR ';'
#else
#include <unistd.h>
#define PATH_SEPARATOR ':'
#endif
#include <iostream>
#include <string>
#include <sstream>
#include <Python.h>
#include "cquacker.h"
std::wstring getSysPath()
{
char cwd[FILENAME_MAX];
getcwd(cwd, FILENAME_MAX);
std::wstringstream path;
path << Py_GetPath() << PATH_SEPARATOR << cwd;
return path.str();
}
int main()
{
Py_Initialize();
PySys_SetPath(getSysPath().c_str());
PyInit_cquacker();
if (PyErr_Occurred())
{
PyErr_Print();
return -1;
}
cquack();
Py_Finalize();
return 0;
}
편집 : 확장 된 예제, 왕복 (C++ -> Python -> C++).
quacker.py :
def qcallback(duck):
duck.quack()
quacker/Duck.hpp
#include <iostream>
namespace quacker {
class Duck
{
public:
void quack() { std::cout << "Quack!" << "\n"; }
};
}
cquacker_defs.pxd :
cdef extern from "quacker/Duck.hpp" namespace "quacker":
cdef cppclass Duck:
Duck() except +
void quack()
cquacker.pyx :
from cython.operator cimport dereference as deref
from libcpp.memory cimport shared_ptr
cimport cquacker_defs
from quacker import qcallback
cdef class Duck:
cdef shared_ptr[cquacker_defs.Duck] _this
@staticmethod
cdef inline Duck _from_this(shared_ptr[cquacker_defs.Duck] _this):
cdef Duck result = Duck.__new__(Duck)
result._this = _this
return result
def __init__(self):
self._this.reset(new cquacker_defs.Duck())
def quack(self):
assert self._this != NULL
deref(self._this).quack()
cdef public void cqcallback(shared_ptr[cquacker_defs.Duck] duck):
qcallback(Duck._from_this(duck))
메인.CPP는 :
#if _WIN32
#include <direct.h>
#define getcwd _getcwd
#define PATH_SEPARATOR ';'
#else
#include <unistd.h>
#define PATH_SEPARATOR ':'
#endif
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include "quacker/Duck.hpp"
#include <Python.h>
#include "cquacker.h"
std::wstring getSysPath()
{
char cwd[FILENAME_MAX];
getcwd(cwd, FILENAME_MAX);
std::wstringstream path;
path << Py_GetPath() << PATH_SEPARATOR << cwd;
return path.str();
}
int main()
{
Py_Initialize();
PySys_SetPath(getSysPath().c_str());
PyInit_cquacker();
if (PyErr_Occurred())
{
PyErr_Print();
return -1;
}
auto duck = std::make_shared<quacker::Duck>();
cqcallback(duck);
Py_Finalize();
return 0;
}
나는 부스트 파이썬을 해본 적이 있지만, 지금까지 내가 기억하는 당신은 C/C에 포함 파이썬에'#INCLUDE을'++ 사용할 수 있습니다. 거기에서 꽤 쉽습니다. [여기 링크] (https://docs.python.org/2/extending/embedding.html). 비록 내가 당신이라면 나는 전체 접근법을 다시 생각할 것입니다. 불필요하게 복잡한 작업을하려고하는 것처럼 들리므로 –
RoughTomato