2017-03-09 99 views
0

我不太瞭解C++,所以我添加了所有的dll代碼。如何將C#託管的結構傳遞給C++非託管DLL並在結果中獲取結構體?

C++ ** ** Calculator.h

#ifndef CALCULATOR_H 
#define CALCULATOR_H 

#include "global.h" 

struct CALCULATORSHARED_EXPORT Input { 
    double a; 
    double b; 
}; 

struct CALCULATORSHARED_EXPORT Result { 
    double sum; 
    double diff; 
    double prod; 
    double div; 
}; 

global.h

#ifndef CALCULATOR_GLOBAL_H 
#define CALCULATOR_GLOBAL_H 

#if defined(CALCULATOR_EXPORTS) 
# define CALCULATORSHARED_EXPORT __declspec(dllexport) 
#else 
# define CALCULATORSHARED_EXPORT __declspec(dllimport) 
#endif 

#endif // CALCULATOR_GLOBAL_H 

calculator.h

#include "calculator.h" 

Result calculate(const Input& input) { 
    Result result; 

    result.sum = input.a + input.b; 
    result.diff = input.a - input.b; 
    result.prod = input.a * input.b; 
    result.div = input.a/input.b; 

    return result; 
} 

C#

[DllImport("Calculator.dll", CallingConvention = CallingConvention.Cdecl)] 
     public static extern Result calculate(Input input); 


     [StructLayout(LayoutKind.Sequential)] 

     public struct Input 
     { 
      public double a; 
      public double b; 
     }; 

     [StructLayout(LayoutKind.Sequential)] 

     public struct Result 
     {    
      public double sum; 
      public double diff; 
      public double prod; 
      public double div; 
     }; 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Input input; 
      Result result; 
      input.a = 5; 
      input.b = 6; 
      result = calculate(input);  
     } 

我越來越Unable to find an entry point named 'calculate' in DLL 'Calculator.dll'.

+0

你其實從出口''Calculator.dll' calculate'? – GSerg

+0

@GSerg我不太明白你的意思是從Calculator.dll導出計算。我已經用這個dll的所有C++代碼更新了我的問題。 – Arbaaz

回答

1

你要做的:

extern "C" 
{ 
    CALCULATORSHARED_EXPORT Result calculate(const Input& input) 
    { 
    } 
} 

你並不需要標記CALCULATORSHARED_EXPORT兩個結構(InputResult)。

extern "C"否則函數的名稱將被損壞,否則CALCULATORSHARED_EXPORT函數將不會被導出。

和C#簽名必須是:

public static extern Result calculate(ref Input input); 

因爲在C++中,它是一個Input&

那麼很顯然

result = calculate(ref input); 
+0

完美!謝謝! – Arbaaz

+0

可以請你告訴我什麼是C#相當於'std :: vector < double > c;'?我將它與輸入結構中的double a和b一起添加到輸入中。如果你想要,我可以把它作爲一個新問題發佈。 – Arbaaz

+1

@Arbaaz沒有希望封送一個'vector <>''。傳遞一個數組+數組的長度 – xanatos