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

时间:2014-10-15 01:12:03

标签: c++ c

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

以下是我的示例代码。

  1. main.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;
    }
    
  2. 头文件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;
       }
      

1 个答案:

答案 0 :(得分:0)

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。