2013-06-05 45 views
0

我得到了一個project.dll和頭文件。它的定義是這樣的:在C中使用C dll中定義的typedef函數#

#ifdef PPSDK_EXPORTS 
#define PP_SDK_API __declspec(dllexport) 
#else 
#define PP_SDK_API __declspec(dllimport) 
#endif 
#ifndef __PP_SDK__ 
#define __PP_SDK__ 

typedef enum 
{ 
    PP_FALSE= 0x0, 
    PP_TRUE = 0x01 
} pp_bool; 

PP_SDK_API pp_bool SDK_Initialize(unsigned long*p_Status); 

我使用一些幫助谷歌和本網站使用此DLL在C#中,但沒有成功。 pp_bool類型錯誤。 這是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
namespace WindowsFormsApplication1 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     [DllImport("project.dll")] 
     static extern pp_bool SDK_Initialize(unsigned long*p_Status); 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 
} 

..................................... 你能幫我怎麼處理它。 謝謝!

+0

您需要確定pp_bool'的'類型。既然它是一個'enum',編譯器就可以使用它想要的任何整數類型,只要該類型可以適合所有的值(並且不大於int除非它必須是) - 所以它可能是bool, short,int,char等等。你需要輸出'sizeof(pp_bool)'來找出你的特定編譯器正在使用什麼類型,然後將它與C#中等價的整數類型進行匹配。另外,在C#端'unsigned long *'應該是'ref uint'(假設C代碼中有32位長)。 – Cameron

回答

0

您的P/Invoke定義不起作用,因爲pp_bool類型在C#中不存在。問題是編譯器在C++中確定了一個enum的大小,所以我們無法確定它的大小。它可能是一個byteshortint。雖然如果它在Visual C++中編譯爲C代碼it looks like it would be an int。我的建議是嘗試每一項並確定哪些作品。

你也可以嘗試聲明返回值爲bool這將是自然的.NET類型。但是,通過default that assumes返回值是32位(int大小)。

在Windows上的C++的P/Invoke定義中存在另一個錯誤,long是一個32位的值,而在.NET中,一個long是64位。所以,你的p_Status應該是一個uint不是unsigned long

而且如果他SDK_Initialize函數只返回一個值unsigned long,你不需要使用指針。改用ref參數。編組人員將負責轉換,您不必使用不安全的代碼。

最後,您需要移動您的p/Invoke定義。 [STAThread]屬性應該在Main()方法上,而不是在p/Invoke定義中。更不用說Main()的文檔註釋正在應用於SDK_Initialize

因此,它應該是這樣的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 

namespace WindowsFormsApplication1 
{ 
    static class Program 
    { 
     [DllImport("project.dll")] 
     static extern bool SDK_Initialize(ref uint p_Status); 

     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 
} 
相關問題