zoukankan      html  css  js  c++  java
  • linux平台上面python调用c

    不能免俗,先打印个helloworld出来,c代码的函数

    hello.c

    #include <stdio.h>
    int helloworld()
    {
        printf("hello world!");
        return 0;
    }

    然后编译成动态链接库

     gcc hello.c -fPIC -shared -o libhello.so  

    最后在python中引入ctypes这个包,然后通过一个对dlopen包装的CDLL就可以引用so中的代码

     import ctypes
     so=ctypes.CDLL("./libhello.so")
     so.helloworld()

    python3和python都能够执行

    python3 main.py                          
     hello world!
    
    python main.py  
    hello world!

    python仅仅支持c代码的这种方式,如果使用c++的编译器,则会报错,例如仅仅是把文件名称替换为hello.cpp

    gcc hello.cpp -fPIC -shared -o libhello.so

    此时再执行

    python ./main.py  

    则出现这种错误

    Traceback (most recent call last):
      File "./main.py", line 15, in <module>
        so=ctypes.CDLL("./libhello.so")
      File "/usr/local/lib/python2.7/ctypes/__init__.py", line 365, in __init__
        self._handle = _dlopen(self._name, mode)
    OSError: ./libhello.so: undefined symbol: __gxx_personality_v0

    用g++更错

    g++ hello.cpp -fPIC -shared -o libhello.so

    则出现

    Traceback (most recent call last):
      File "./main.py", line 16, in <module>
        so.helloworld()
      File "/usr/local/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__
        func = self.__getitem__(name)
      File "/usr/local/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__
        func = self._FuncPtr((name_or_ordinal, self))
    AttributeError: ./libhello.so: undefined symbol: helloworld
  • 相关阅读:
    事件委托
    a标签深入研究
    windows查看端口号
    什么是WCM
    map key循环
    用Myeclipse打war包
    myeclipse 8.510.0 安装 svn 方法
    SVN使用&CVS使用
    MyEclipse 字体大小 字体颜色
    什么是Quickr
  • 原文地址:https://www.cnblogs.com/laodageblog/p/3757867.html
Copyright © 2011-2022 走看看