2012-09-30 71 views
2

我想使用DLLImport在C#中使用Win32 dll方法。DLL導入:無法找到入口點「fnMultiply」在DLL「ImportDLL」

的Win32 DLL C++ // h文件

#ifdef IMPORTDLL_EXPORTS 
#define IMPORTDLL_API __declspec(dllexport) 
#else 
#define IMPORTDLL_API __declspec(dllimport) 
#endif 

// This class is exported from the ImportDLL.dll 
class IMPORTDLL_API CImportDLL { 
public: 
    CImportDLL(void); 
    // TODO: add your methods here. 
    int Add(int a , int b); 
}; 

extern IMPORTDLL_API int nImportDLL; 

IMPORTDLL_API int fnImportDLL(void); 
IMPORTDLL_API int fnMultiply(int a,int b); 

// cpp文件

// ImportDLL.cpp:定義導出的函數爲DLL應用。 //

#include "stdafx.h" 
#include "ImportDLL.h" 


// This is an example of an exported variable 
IMPORTDLL_API int nImportDLL=0; 

// This is an example of an exported function. 
IMPORTDLL_API int fnImportDLL(void) 
{ 
    return 42; 
} 

IMPORTDLL_API int fnMultiply(int a , int b) 
{ 
    return (a*b); 
} 

一旦我建立這個我得到ImportDLL.dll

現在我創建的Windows應用程序和debug文件夾中添加此DLL並嘗試使用的DllImport

[DllImport("ImportDLL.dll")] 
public static extern int fnMultiply(int a, int b); 

使用此方法我嘗試在C#中調用它 int a = fnMultiply(5, 6); //此行給出錯誤無法找到入口點

任何機構可以告訴我缺少什麼? 謝謝。

+0

@HansPassant氏s不是一個實例方法。它是DLL中的常規公共函數。檢查標題decl。實際上,這是股票「創建一個帶導出符號的DLL」項目,由VS吐出。他不是在試圖挑戰實例方法,他正在嘗試連接一個導出的函數。 – WhozCraig

+0

你是對的,被班級絆倒了。 –

回答

2

如果您是從本機DLL導出C函數,你可能需要使用__stdcall calling convention(這相當於WINAPI,即大多數的Win32 API的C接口函數使用的調用約定,並且是對於.NET的P/Invoke默認):

extern "C" MYDLL_API int __stdcall fnMultiply(int a, int b) 
{ 
    return a*b; 
} 

// Note: update also the .h DLL public header file with __stdcall. 

另外,如果你想避免名字改編,你可能要export using .DEF files。 例如.def文件添加到您的本機DLL項目,並編輯其內容是這樣的:

LIBRARY MYDLL 
EXPORTS 
    fnMultiply @1 
    ... 

(您可以使用命令行工具DUMPBIN/EXPORTS,或GUI工具,如Dependency Walker,檢查隨着其功能是從DLL導出實際名稱)

然後你可以使用P /從C#調用是這樣的:

[DllImport("MyDLL.dll")] 
public static extern int fnMultiply(int a, int b); 
1

關閉您的導出功能的名稱修改。應該大力協助。另外,你可以加載名稱損壞(有一種方法來配置DllImport屬性來做到這一點,所以我聽到了,但我不是一個C#工程師,所以我把它留給你,看看它是否存在)。

extern "C" IMPORTDLL_API int fnMultiply(int a , int b) 
{ 
    return (a*b); 
} 
相關問題