I have following code in my myPyTest.c file
#include<python/Python.h>
#include "libtest.h"
static PyObject * callThatFunc(PyObject *self, PyObject *args) {
const char *a, *b, *c;
if (!PyArg_ParseTuple(args, "S", &a, &b, &c))
return NULL;
printf("%s", returnThis(a));
return PyString_FromString(b);
}
static PyMethodDef BarMethods[] = {
{"call_bar", callThatFunc, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initbar(void)
{
(void) Py_InitModule("bar", BarMethods);
}
int main() {
printf("Hello");
return 0;
}
check this for above code
Now I have following golang code in my_go_call.go file.
package main
import "C"
//export returnThis
func returnThis(myString *C.char) *C.char {
var result *C.char
myStringGo := C.GoString(myString)
result = C.CString("Hello, " + myStringGo)
return result
}
func main() {
}
I have created shared library using command (MAC)
go build -ldflags -s -buildmode=c-shared -o libtest.so my_go_call.go
Then I have setup.py file to build c extension for python. Code of setup.py as follows
from distutils.core import setup, Extension
module1 = Extension('bar',
libraries = ['test'],
library_dirs = ['/path/to/lib'],
sources = ['myPyTest.c'])
setup (name = 'PackageName',version = '1.0',description = 'This is a demo package',ext_modules = [module1])
Now i am building and installing my extension using following commands
python setup.py build
python setup.py install
whenever I call my function in python interpreter i get following error.
>>> import bar
>>> dir(bar)
['__doc__', '__file__', '__name__', '__package__', 'call_bar']
>>> bar.call_bar('a','b','c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 1 argument (3 given)