2011-11-22 45 views
1

當我訪問具有雙指針作爲參數的函數時,我對swig非常陌生,並且得到了一個奇怪的TypeError。TypeError:無法使用雙指針參數訪問包裝函數

這裏是我的文件:

Example.hpp

#ifndef _EXAMPLE_HPP 
#define _EXAMPLE_HPP 

class Example { 
public: 
    void test_cc(char * c0, char * c1); 
    void test_cd(char * c0, double d0); 
    void test_cdp(char * c0, double * d0); 
}; 

#endif // _EXAMPLE_HPP 

Example.cpp

#include "Example.hpp" 

void Example::test_cc(char * c0, char * c1) {} 
void Example::test_cd(char * c0, double d0) {} 
void Example::test_cdp(char * c0, double * d0) {} 

Example.i

%module Example 
%{ 
#include "Example.hpp" 
%} 

#include "Example.hpp" 

最後我testfile的test_Example.py :

#!/usr/bin/env python 

import Example 

E = Example.Example() 

E.test_cc("Hello","World"); 
E.test_cd("Hello",42); 
E.test_cdp("Hello",42); 

當我運行./test_Example.py,我得到錯誤信息

Traceback (most recent call last): 
    File "./test_Example.py", line 9, in <module> 
    E.test_cdp("Hello",42); 
    File "Example.py", line 77, in test_cdp 
    def test_cdp(self, *args): return _Example.Example_test_cdp(self, *args) 
TypeError: in method 'Example_test_cdp', argument 3 of type 'double *' 

訪問test_cc工作的功能,test_cd也......爲什麼不test_cdp?

我的錯誤在哪裏?

回答

1

我認爲你的問題其實是:

void test_cd(char * c0, double * d0); 

和你的參數應該是一個double,而不是一個double*

關於你的評論

你的代碼是:

E.test_cc("Hello","World"); 
E.test_cd("Hello",42); 

你的原型是:

void test_cc(char * c0, char * c1); 
void test_cd(char * c0, double d0); 

「你好」 和 「世界」 是字符串文字衰變到類型爲const char *。所以,他們是指針。當你在test_cc中傳遞c0和c1時,因爲它需要一個指針。

while c0是test_cd中的指針,d0不是--d0的類型是double,NOT指針是double。所以,你必須傳遞一個指向double的指針。

您可以通過創建一個雙堆棧上,並通過在其地址做到這一點:

double hi_mom = 83.2; 
test_cd("some string" &hi_mom); 

或聲明指針,使之指向一個堆棧變量,通過在:

double hi_mom = 83.2; 
double* ptr = &hi_mom; 
test_cd("some string", ptr); 

或通過聲明一個指針指向動態存儲器中並通過在:

double* ptr = new double(83.2); 
test_cd("some string", ptr); 
delete ptr; 

儘管如果可以,我會避開第三個。

再次編輯...

http://www.dalkescientific.com/writings/NBN/c_extensions.html

示出如何從包括蟒傳遞一個雙調用C代碼的工作示例。在python和C代碼中搜索iterate_point,看看它是如何工作的。你不應該有一個雙倍的指針,它應該是前面所說的正常的雙倍。

+0

我想從python訪問C++ fcuntion test_cdp,而不是從C++。 – redimp

+0

再次編輯答案......但這是我首先說的。我這次提供了一個工作示例。 –

+0

我想通過一個雙*。不是雙倍。 test_cd的作品,但不是我想要的。 iterate_point也會增加一倍。不是雙倍*。 – redimp