0
1

More than 3 years have passed since last update.

眺めて覚えるC言語 その2 PythonからC言語を呼ぶ(引数) string

Last updated at Posted at 2020-01-06
capi.py
import myModule as capi
print(capi.Message("こんにちは、日本"))

実行する
capi>python capi.py
こんにちは日本
こんにちは日本
capilib.c
#include <Python.h>

static PyObject* Message(PyObject* self, PyObject* args){
    char* str;
    if (!PyArg_ParseTuple(args, "s",&str)){
        return NULL;
    }
    printf("%s\n",str);
    return Py_BuildValue("s", str);
}
// Function Definition struct
static PyMethodDef myMethods[] = {
    { "Message", Message, METH_VARARGS, "Prints Message"},
    { NULL }
};
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,"myModule","C API Module",-1,myMethods
};
PyMODINIT_FUNC PyInit_myModule(void){
    return PyModule_Create(&myModule);
}

注目ポイント

char* str;
//引数の取り込み
if (!PyArg_ParseTuple(args, "s",&str)){
    return NULL;
}
//戻り値の作成
return Py_BuildValue("s", str);
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1