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
  • 相关阅读:
    iOS微信支付集成
    iOS支付宝支付集成
    JavaScript原生实现《贪吃蛇》
    安装tensorflow的最简单方法(Ubuntu 16.04 && CentOS)
    Eclipse 插件管理
    settings.xml 文件配置
    Spring MVC 起步
    机器学习: KNN--python
    Python: PS 图像调整--亮度调整
    计算机设计思想 —— 代理(proxy)
  • 原文地址:https://www.cnblogs.com/laodageblog/p/3757867.html
Copyright © 2011-2022 走看看