我的myPyTest.c文件中有以下代码
#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;
}
检查this以获取上述代码
现在我在my_go_call.go文件中有以下golang代码。
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() {
}
我使用命令(MAC)创建了共享库
go build -ldflags -s -buildmode=c-shared -o libtest.so my_go_call.go
然后我有setup.py文件为python构建c扩展。 setup.py代码如下
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])
现在我正在使用以下命令构建和安装我的扩展程序
python setup.py build
python setup.py install
每当我在python解释器中调用我的函数时,我都会遇到以下错误。
>>> 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)