从C++函数到C函数的返回指针
return pointer from C++ function to C function
我还是C和C++编程的初学者。我目前正在开发一个代码,从C调用C++中的一个函数。这是因为我的主要代码是用C编写的,我需要使用用C++编写的某些库。我正在使用Eigen库来实现这种方法。我目前在将C++中产生的值返回到C时遇到问题。我想将(a)从*.cpp返回到*.C,并在*.C中预览结果(printf)。
这是我的示例代码。
-
主.c 中的主代码
#include "lib2run.h" #include "stdio.h" int main () { struct C_MatrixXd *matrix1; matrix1 = play_matrix (); printf("Here is matrix1:n"); MatrixXd_print(matrix1); // <-- I want to use printf to print matrix1, not like this return 0; }
头文件lib2run.h
#ifdef __cplusplus
extern "C"
{
#endif
struct C_MatrixXd* play_matrix ();
void MatrixXd_print (const struct C_MatrixXd *m);
#ifdef __cplusplus
} // end extern "C"
#endif
这是lib2run.cpp 中的代码
#include <iostream> #include <Eigenvalues> #include <Core> #include "lib2run.h" using namespace Eigen; using Eigen::MatrixXd; using Eigen::EigenSolver; inline C_MatrixXd* eigen_to_c(MatrixXd& ref) { return reinterpret_cast<C_MatrixXd*>(&ref); } inline MatrixXd& c_to_eigen(C_MatrixXd* ptr) { return *reinterpret_cast<MatrixXd*>(ptr); } inline const MatrixXd& c_to_eigen(const C_MatrixXd* ptr) { return *reinterpret_cast<const MatrixXd*>(ptr); } C_MatrixXd* play_matrix () { MatrixXd A = MatrixXd::Random(3,3); std::cout << "Here is a random 3x3 matrix, A:" << std::endl << A << std::endl << std::endl; EigenSolver<MatrixXd> es(A); MatrixXd D = es.pseudoEigenvalueMatrix(); MatrixXd V = es.pseudoEigenvectors(); std::cout << "The pseudo-eigenvalue matrix D is:" << std::endl << D << std::endl<< std::endl; std::cout << "The pseudo-eigenvector matrix V is:" << std::endl << V << std::endl<< std::endl; std::cout << "Finally, V * D * V^(-1) = " << std::endl << V * D * V.inverse() << std::endl<< std::endl; return eigen_to_c (A); } void MatrixXd_print(const C_MatrixXd *m) { std::cout << c_to_eigen(m) << std::endl; }
C和C++幸福地生活在一起。问题是@jxh指出的。您正在返回一个指向使用该点时将不存在的对象的指针。在您的情况下,为了尽可能少地修改代码,您应该使用new
来分配MatrixA。
// Allocate a new matrix which will live beyond this function
MatrixXd* A = new MatrixXd(3,3);
// Copy a random matrix to it
*A = MatrixXd::Random(3,3);
// ...
return A;
如果可以的话,我也会把你的main.c
改为main.cpp
,用C++编译器(比如g++)编译,然后废弃你的C_MatrixXd。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量