簡體   English   中英

將C ++雙重返回Python?

[英]Return C++ double to Python?

所以我使用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的整數。發生了什么?

我也對通過引用填充數組感到好奇。

來自ctypes文檔

默認情況下,假定函數返回C int類型。 可以通過設置函數對象的restype屬性來指定其他返回類型。

如果您將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM