首页 / PYTHON / 将C返回到Python?
将C返回到Python?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将C返回到Python?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1264字,纯文字阅读大概需要2分钟。
内容图文
![将C返回到Python?](/upload/InfoBanner/zyjiaocheng/826/51c5e2e4be854274b109f80b0e76e7bd.jpg)
所以我使用python来调用共享C库中的方法.我有一个问题从C返回到python.我有一个创建了一个展示问题的玩具示例.随意编译并试用.
这是python代码(soexample.py):
# Python imports
from ctypes import CDLL
import numpy as np
# Open shared CPP library:
cpplib=CDLL('./libsoexample.so')
cppobj = cpplib.CPPClass_py()
# Stuck on converting to short**?
x = cpplib.func_py(cppobj)
print 'x =', x
这是C(soexample.cpp):
#include <iostream>
using namespace std;
class CPPClass
{
public:
CPPClass(){}
void func(double& x)
{
x = 1.0;
}
};
// For use with python:
extern "C" {
CPPClass* CPPClass_py(){ return new CPPClass(); }
double func_py(CPPClass* myClass)
{
double x;
myClass->func(x);
return x;
}
}
编译:
g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp
当我跑步时,我得到:
$python soexample.py
x = 0
所以结果是类型和值为0的整数.发生了什么?
我也对通过引用填充数组感到好奇.
解决方法:
By default functions are assumed to return the C
int
type. Other
return types can be specified by setting therestype
attribute of the
function object.
如果您将func_py的使用更改为以下内容,则此方法有效:
import ctypes
func_py = cpplib.func_py
func_py.restype = ctypes.c_double
x = func_py(cppobj)
print 'x =', x
虽然它可能适用于这种简单的情况,但您也应该指定CPPClass_py.restype.
内容总结
以上是互联网集市为您收集整理的将C返回到Python?全部内容,希望文章能够帮你解决将C返回到Python?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。