2016-10-19 37 views
2

저는 파이썬 클래스 A을 가지고 있습니다.C++, PyObject의 매개 변수로 파이썬 생성자를 생성하십시오.

class A: 
    def __init__(self, name): 
     self.name = name 

    def print_lastname(self, lastname): 
     print(lastname) 

이 코드를 다음과 같이 호출해야합니다.

import B 
a = B.A("hello") 
a.print_lastname("John") 

현재, 나는 내 C++ 코드에서이 A 클래스를 사용해야합니다. 나는 이걸 가지고있다.

Py_Initialize(); 
string hello = "hello"; 
PyObject *module, *attr, *arg; 
module = PyObject_ImportModule("B"); // import B 
attr = PyObject_GetAttrString(module, "A"); // get A from B 
arg = PyString_FromString(hello.c_str()); 
instance = PyInstance_New(attr, arg, NULL); // trying to get instance of A with parameter "hello" 
Py_Finalize(); 

하지만 오류

Exception TypeError: 'argument list must be tuple' in module 'threading' from '/usr/lib64/python2.7/threading.pyc'

가 어떻게 C++에서 a.print_name("John")import 문에서 달성 할 수는 무엇입니까? 도움을 주시면 감사하겠습니다.

답변

5

저는 파이썬 클래스를 약간 재 작성하려고합니다. 단지 인자와 멤버 변수를 모두 사용하기 때문입니다. 는 C++ 부분으로

# B.py - test module 
class A: 
    def __init__(self, name): 
     self.name = name 

    def print_message(self, message): 
     print message + ' ' + self.name 

거의 모든 것이 괜찮아 보인다. PyInstance_New에 대한 인수가 튜플이어야하기 때문에 오류가 발생합니다. 함수 나 메소드를 호출하는 방법은 여러 가지가 있습니다. 다음은 그 중 하나를 사용하는 전체 예제입니다.

// test.c - test embedding. 
void error_abort(void) 
{ 
    PyErr_Print(); 
    exit(EXIT_FAILURE); 
} 

int main(int argc, char* argv[]) 
{ 
    PyObject* temp, * args, * attr, * instance; 

    Py_Initialize(); 
    if (!(temp = PyString_FromString("John"))) 
     error_abort(); 
    if (!(args = PyTuple_Pack(1, temp))) 
     error_abort(); 
    Py_DECREF(temp); 

    if (!(temp = PyImport_ImportModule("B"))) 
     error_abort(); 
    if (!(attr = PyObject_GetAttrString(temp, "A"))) 
     error_abort(); 
    Py_DECREF(temp); 

    if (!(instance = PyInstance_New(attr, args, NULL))) 
     error_abort(); 
    if (!PyObject_CallMethod(instance, "print_message", "s", "Hello")) 
     error_abort(); 

    Py_DECREF(args); 
    Py_DECREF(attr); 
    Py_DECREF(instance); 
    Py_Finalize(); 
    return 0; 
} 

자세한 내용은 Python pure-embedding을 참조하십시오.

+0

매우 멋지다! 매력처럼 작동합니다. – pseudo

+0

굉장 - 고마워! –