加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

有关从C创建Python库的建议吗?

发布时间:2020-12-16 07:12:06 所属栏目:百科 来源:网络整理
导读:我最近使用OpenGL库在C中创建了一个3D和2D力布局图可视化器(它使用了一些物理特性).有人可以给我一些关于使这个作为 Python库有用的介绍性指针(问题或考虑因素以及我可能遇到的潜在陷阱)吗? 解决方法 如果我正确理解您的问题,您想知道如何编写C扩展以便在Py
我最近使用OpenGL库在C中创建了一个3D和2D力布局图可视化器(它使用了一些物理特性).有人可以给我一些关于使这个作为 Python库有用的介绍性指针(问题或考虑因素以及我可能遇到的潜在陷阱)吗?

解决方法

如果我正确理解您的问题,您想知道如何编写C扩展以便在Python中使用.这是一个简单的例子:

你好?:

#include <Python.h>

static PyObject* helloworld(PyObject* self)
{
    return Py_BuildValue("s","Hello,Python extensions!!");
}

static char helloworld_docs[] =
    "helloworld( ): Any message you want to put here!!n";

static PyMethodDef helloworld_funcs[] = {
    {"helloworld",(PyCFunction)helloworld,METH_NOARGS,helloworld_docs},{NULL}
};

void inithelloworld(void)
{
    Py_InitModule3("helloworld",helloworld_funcs,"Extension module example!");
}

setup.py:

#!/usr/bin/env python

from setuptools import setup,Extension

setup(
    name='helloworld',version='1.0',ext_modules=[
        Extension('helloworld',['hello.c'])
    ]
)

建立:

$python setup.py develop
running develop
running egg_info
creating helloworld.egg-info
writing helloworld.egg-info/PKG-INFO
writing top-level names to helloworld.egg-info/top_level.txt
writing dependency_links to helloworld.egg-info/dependency_links.txt
writing manifest file 'helloworld.egg-info/SOURCES.txt'
reading manifest file 'helloworld.egg-info/SOURCES.txt'
writing manifest file 'helloworld.egg-info/SOURCES.txt'
running build_ext
building 'helloworld' extension
creating build
creating build/temp.linux-x86_64-2.7
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c hello.c -o build/temp.linux-x86_64-2.7/hello.o
creating build/lib.linux-x86_64-2.7
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/hello.o -o build/lib.linux-x86_64-2.7/helloworld.so
copying build/lib.linux-x86_64-2.7/helloworld.so -> 
Creating /home/prologic/.virtualenvs/hellopyc/lib/python2.7/site-packages/helloworld.egg-link (link to .)
Adding helloworld 1.0 to easy-install.pth file

Installed /home/prologic/tmp/hello-py-c
Processing dependencies for helloworld==1.0
Finished processing dependencies for helloworld==1.0

测试:

$python
Python 2.7.6 (default,Mar 22 2014,22:59:56) 
[GCC 4.8.2] on linux2
Type "help","copyright","credits" or "license" for more information.
>>> import helloworld
>>> helloworld.helloworld()
'Hello,Python extensions!!'
>>>

祝好运!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读