从C++函数到C函数的返回指针

return pointer from C++ function to C function

本文关键字:函数 返回 指针 C++      更新时间:2023-10-16

我还是C和C++编程的初学者。我目前正在开发一个代码,从C调用C++中的一个函数。这是因为我的主要代码是用C编写的,我需要使用用C++编写的某些库。我正在使用Eigen库来实现这种方法。我目前在将C++中产生的值返回到C时遇到问题。我想将(a)从*.cpp返回到*.C,并在*.C中预览结果(printf)。

这是我的示例代码。

  1. 主.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
  1. 这是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。