[英]creating a python module using ctypes
I have a C library with only two functions: char *foo_decode(const char*)
and const char *foo_version()
.我有一个 C 库,只有两个函数:
char *foo_decode(const char*)
和const char *foo_version()
。
I now want to create a python module that allows to call these two functions.我现在想创建一个允许调用这两个函数的 python 模块。
The C library is compiled into foo.so
. C 库被编译成
foo.so
。
This is my python module file:这是我的 python 模块文件:
$ cat foo.py
import ctypes as ct
_lib = ct.cdll.LoadLibrary("./foo.so")
_lib.foo_decode.argtypes = [ct.c_char_p]
_lib.foo_decode.restype = ct.c_char_p
_lib.foo_version.argtypes = []
_lib.foo_version.restype = ct.c_char_p
def decode(fooText):
return _lib.foo_decode(fooText.encode('utf8')).decode('utf-8')
def version():
return _lib.foo_version().decode('utf-8')
I followed this tutorial .我跟着这个教程。
When I start a python3 interpreter and execute this manually.当我启动 python3 解释器并手动执行它时。 Everything works fine.
一切正常。 I can call the functions and I get back the expected result.
我可以调用这些函数并得到预期的结果。
But when I import my module file ( import foo
) I get the error ImportError: dynamic module does not define module export function (PyInit_foo)
.但是当我导入我的模块文件(
import foo
)时,我收到错误ImportError: dynamic module does not define module export function (PyInit_foo)
。
What is happening and what should I do to fix this problem?发生了什么,我应该怎么做才能解决这个问题?
My goal is to produce a package downloadable with pip install.我的目标是通过 pip 安装生成可下载的 package。 Am I on the right track?
我在正确的轨道上吗? I don't want wheels since the code is small and has no dependencies.
我不想要轮子,因为代码很小并且没有依赖关系。 I should thus compile fast and should be very portable.
因此,我应该快速编译并且应该非常便携。
You have a shared library foo.so
and a module foo.py
.你有一个共享库
foo.so
和一个模块foo.py
。 When Python does import foo
it loads only one of them;当 Python 确实
import foo
它只加载其中一个; in your case it's foo.so
;在您的情况下,它是
foo.so
; but foo.so
is not a Python module hence the error.但
foo.so
不是 Python 模块,因此出现错误。
Rename your foo.py
to something different like foo_wrapper.py
and try import foo_wrapper
.将您的
foo.py
重命名为不同的名称,例如foo_wrapper.py
并尝试import foo_wrapper
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.