2
我不明白爲什麼值會從func1丟到func2然後是main。它可以在func1中打印,但在func2和main中失敗。 我不認爲這是一個swig問題,更像是一個C++代碼問題〜你可以用下面的代碼重現問題。函數之間的數組指針丟失值(用swig在python3中編譯使用)
我TEST.CPP:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <mutex>
#include "test.h"
void test::func1(float* feat) {
std::vector<float> fv = {1,2,3,4,5,6,7};
feat = fv.data();
for (std::size_t i = 0; i < 7; ++i){
std::cout << *feat << std::endl;
feat++;
}
}
bool test::func2(float* feat) {
test::func1(feat);
}
bool test::main(float* feat){
test::func2(feat);
for (std::size_t i = 0; i < 7; ++i){
std::cout << *feat << std::endl;
feat++;
}
}
我test.h:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <mutex>
class test {
public:
void func1(float* feat);
bool func2(float* feat);
bool main(float* feat);
};
我test.i:
%module test
%{
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include "carrays.i"
%array_functions(float, floatArray);
%include <std_string.i>
%include "test.h"
當我在python3測試:
>>> from test import test, new_floatArray, floatArray_getitem
>>> import numpy as np
>>> pp = test()
>>> temp = new_floatArray(5)
>>> pp.main(temp)
1
2
3
4
5
6
7
0
0
0
0
0
4.02252e-14
1.4013e-44
False
非常感謝!所以,指針浮點*的點只保留在本地,不會超出範圍? – ayy
因爲您按值傳遞指針。在任何情況下,fv中數據的生命週期只會延伸到func1的末尾。如果您通過引用傳遞指針並將其更改爲指向fv的數據。這將成爲一個懸掛指針,這是非法的。 – Frank