download1323 2017-10-18 07:53
浏览 122

使用C从python调用golang函数

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)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 django项目运行报编码错误
    • ¥15 请问这个是什么意思?
    • ¥15 STM32驱动继电器
    • ¥15 Windows server update services
    • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
    • ¥15 模糊pid与pid仿真结果几乎一样
    • ¥15 java的GUI的运用
    • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
    • ¥15 怎么配置广告联盟瀑布流
    • ¥15 Rstudio 保存代码闪退