일부 C ++ 코드로 파이썬을 확장하려고합니다. 나는 여기 가이드를 고수했습니다
https://docs.python.org/2/extending/extending.html
표준 헤더 spammodule.h를 사용합니다.
#ifndef Py_SPAMMODULE_H
#define Py_SPAMMODULE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Header file for spammodule */
/* C API functions */
#define PySpam_System_NUM 0
#define PySpam_System_RETURN int
#define PySpam_System_PROTO (const char *command)
/* Total number of C API pointers */
#define PySpam_API_pointers 1
#ifdef SPAM_MODULE
/* This section is used when compiling spammodule.c */
static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
#else
/* This section is used in modules that use spammodule's API */
static void **PySpam_API;
#define PySpam_System \
(*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
/* Return -1 on error, 0 on success.
* PyCapsule_Import will set an exception if there's an error.
*/
static int
import_spam(void)
{
PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
return (PySpam_API != NULL) ? 0 : -1;
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* !defined(Py_SPAMMODULE_H) */
실제 기능은 spam.cpp 파일에 저장됩니다.
#define SPAM_MODULE
#include "spammodule.h"
#include <Python.h>
#include <iostream>
static PyObject * some_other_method(PyObject *self, PyObject *args);
static PyObject * spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
system(command);
sts = 2;
return Py_BuildValue("i", sts);
}
static int
PySpam_System(const char *command)
{
return system(command);
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{"some_other_method", some_other_method, METH_VARARGS, "do new stuff"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
파일 method.cpp에 넣어
#include <Python.h>
#include <iostream>
static PyObject * some_other_method(PyObject *self, PyObject *args){
std::cout<<"hello world\n"<<std::endl;
int sts = 2;
return Py_BuildValue("i", sts);
}
이것은 경고와 함께 컴파일됩니다.
spam.cpp:7:19: warning: ‘PyObject* some_other_method(PyObject*, PyObject*)’ used but never defined [enabled by default]
static PyObject * some_other_method(PyObject *self, PyObject *args);
파이썬 스크립트에서 가져올 때 실패합니다.
import spam
spam.system("ls -l")
spam.some_other_method()
그러나 some_other_method의 전방 선언을 실제 코드로 대체하면
//static PyObject * some_other_method(PyObject *self, PyObject *args);
#include "method.cpp"
잘 작동합니다.
함수 static
가 정의 된 경우 cpp 파일에서만 볼 수 있습니다. 다른 cpp 파일에서 호출 할 수 없습니다 (먼저 함수에 대한 포인터를 얻지 않는 한).
static
자신의 소스 파일 외부에서 볼 수있는 함수에서 제거해야 합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다