c++ - 函数之间的数组指针丢失值(用 swig 编译以在 python3 中使用)

标签 c++ arrays function pointers swig

我不明白为什么值会从 func1 到 func2 然后再到 main 丢失。它在 func1 中打印正常,但在 func2 和 main 中失败。 我觉得不是swig的问题,更像是c++代码的问题~你可以用下面的代码重现问题。

我的测试.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++;
    }
}

我的测试.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);
};

我的测试.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

最佳答案

feat = fv.data();

这一行并没有改变feat指向的数据,它改变了本地版本的feat指向的数据。

因此当您从 func2() 返回时,feat 和它指向的数据都没有改变。由于您将未初始化的数据传递给 main,因此您会从 func 1(来自它自己的数据)中获得 7 个打印,然后是 7 个未初始化数据的打印,这将是任何内容。

我怀疑你的意思是:

memcpy(feat, fv.data(), fv.size() * sizeof(float));

这会将数据从 fv 复制到数据 feat 指向。

关于c++ - 函数之间的数组指针丢失值(用 swig 编译以在 python3 中使用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187806/

相关文章:

python - 将参数作为用户输入的函数

Javascript 函数无法运行

c++ - 创建一个返回指向类模板对象的共享指针的函数

c++ - 打开文本文件并读取带有空格的字符串,然后将 2 个单独的整数放入结构中

c++ - 将文本文件读取为字符串的最短方法

C++ delete 在某些实例上崩溃

arrays - 使用 SwiftyJSON 读取 JSON 响应的子节点

javascript - Angular - 如何优化代码以缩短加载时间?当前加载时间为 2.45 秒

c++ - 结构数组中按字母顺序排序的问题气泡

python - Python 函数中的动态输出