2017-10-18 07:53 阅读 119


I have following code in my myPyTest.c file

#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}

    (void) Py_InitModule("bar", BarMethods);

int main() {
    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 my_go_call.go

Then I have file to build c extension for python. Code of 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 build
python 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)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享