简体   繁体   English

仅用python包装AC库

[英]Wrap a c library with python only

I was provided with ac library wave.so, with a function interfaced defined, I follow the guide here 为我提供了一个ac库wave.so,并定义了接口函数,请按照此处的指南进行操作

https://stackoverflow.com/a/5868051/2789784 https://stackoverflow.com/a/5868051/2789784

and it works. 而且有效。 However, when I made the script to be a file MyModule.py, and try to import by 但是,当我将脚本设为文件MyModule.py并尝试通过

import MyModule

Then it gives me this error. 然后它给了我这个错误。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initwave)

Why does this happen? 为什么会这样? How should I fix it? 我应该如何解决?

FIXED: so I have both MyModule.py and MyModule.so at the same folder, python tried to load MyModule.so instead of MyModule.py, and of course he cannot be successful, change the name of MyModule.py to wave.py and 修正:所以我在同一个文件夹中都有MyModule.py和MyModule.so,python尝试加载MyModule.so而不是MyModule.py,当然他不能成功,将MyModule.py的名称更改为wave.py和

import wave 

solves the problem. 解决了问题。 So basically if you just want to call some c++ library function, you really just need a python script wrapper and that's it, no c-programming. 因此,基本上,如果您只想调用某些c ++库函数,则实际上只需要一个python脚本包装器即可,仅此而已,无需c编程。 And I can use my c++ shared library for other application too. 而且我也可以将c ++共享库用于其他应用程序。

When you write an extension module in C there must be a module init function. 用C编写扩展模块时,必须有一个模块初始化函数。 If your module is called wave , there must be a function called initwave in the extension module. 如果您的模块名为wave ,那么扩展模块中必须有一个名为initwave的函数。 A simple example would be: 一个简单的例子是:

static PyMethodDef methods[] = {
    /* methods go here, if any */
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initwave(void){
Py_InitModule3("wave", methods, "this is the doc string");
}

Then compile the extension with something like: 然后使用以下内容编译扩展:

Extension('wave',
    ['source_file.c', 'another_source_file.c'],
)

The extension module that you can import is called wave.so , (I don't know if renaming it is safe, but its definitely no good idea) In your python script MyModule.py simply do: 您可以导入的扩展模块称为wave.so ,(我不知道重命名是否安全,但是绝对不是个好主意)在您的python脚本MyModule.py只需执行以下操作:

import wave 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM