I tried to make a program written in C usable from Python 3 All the references are old and I had a hard time making it compatible with Python3 ...
hello.c
int add(int x, int y)
{
return x + y;
}
void out(const char* adrs, const char* name)
{
printf("Hello, I%s%s.\n", adrs, name);
}
This is the C source code, which has two functions, add and out.
helloWrapper.c
#include "Python.h"
extern int add(int, int);
extern void out(const char*, const char*);
PyObject* hello_add(PyObject* self, PyObject* args)
{
int x, y, g;
if (!PyArg_ParseTuple(args, "ii", &x, &y))
return NULL;
g = add(x, y);
return Py_BuildValue("i", g);
}
PyObject* hello_out(PyObject* self, PyObject* args, PyObject* kw)
{
const char* adrs = NULL;
const char* name = NULL;
static char* argnames[] = {"adrs", "name", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "|ss",
argnames, &adrs, &name))
return NULL;
out(adrs, name);
return Py_BuildValue("");
}
static PyMethodDef hellomethods[] = {
{"add", hello_add, METH_VARARGS},
{"out", hello_out, METH_VARARGS | METH_KEYWORDS},
{NULL}
};
static struct PyModuleDef hellomodule =
{
PyModuleDef_HEAD_INIT,
"hellomodule", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
hellomethods
};
PyMODINIT_FUNC PyInit_hellomodule(void)
{
return PyModule_Create(&hellomodule);
}
This is the main source code.
See here for the meaning of each program → Call a C program from Python
Execute three commands.
gcc -fpic -o hello.o -c hello.c
gcc -fpic -I`python3-config --prefix`/Headers -o helloWrapper.o -c helloWrapper.c
gcc -L`python3-config --prefix`/lib -lpython3.5 -shared hello.o helloWrapper.o -o hellomodule.so
python3-config--prefix
and compile helloWrapper.c.python3-config--prefix
with -L to create the library.Let's try it out, is it really done?
hnkz $ python3
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hellomodule
>>> hellomodule.add(2,3)
5
>>> hellomodule.out("hamamatsu","hnkz")
Hello, I am hnkz of hamamatsu.
It's done! Wow! !!
I want to apply it and make a keylogger with Python3.
Call a C program from Python I tried C binding in Python Compiler can't find Py_InitModule() .. is it deprecated and if so what should I use?
Recommended Posts