2013-06-18 24 views
0

我創建了一個帶有CLR選項的Visual Studio 2010中的C++/cli dll,如下所示,並創建了email.dll。然後測試了這一點創造了另一個VS2010 Win32項目,並試圖加載使用調用LoadLibrary這是alwyas返回NULL的email.dll:LoadLibrary無法加載C++ CLI創建的dll

HINSTANCE hGetProcIDDLL = LoadLibrary((LPCWSTR)"pathto\\email.dll");

我的問題是:應該在email.dll可以以其他方式加載?或者如果正確創建了email.dll。

email.cpp的C++/CLI代碼:定義DLL應用程序的導出函數。

#using <mscorlib.dll> 
#using <system.dll> 
include "stdafx.h" 
using namespace System; 

using namespace System::Net::Mail; 


extern int CallSendEmailFromGmail(char* fromEmail, char* password, char* toEmail, char* subject, char* message); 


extern "C" 
{ 
    __declspec(dllexport) int SendEmailFromGmail(char* fromEmail, char* password, char* toEmail, char* subject, char* message) 
    { 
     return CallSendEmailFromGmail(fromEmail, password, toEmail, subject, message); 
    } 

} 

int CallSendEmailFromGmail(char* fromEmail, char* password, char* toEmail, char* subject, char* message) 
{ 

     String ^from = gcnew String(fromEmail); 
     String ^pwd = gcnew String(password); 
     String ^to = gcnew String(toEmail); 
     String ^subjectStr = gcnew String(subject); 
     String ^messageStr = gcnew String(message); 
     SmtpClient ^client = gcnew SmtpClient(); 
// client->DeliveryMethod = SmtpDeliveryMethod.Network; 

     client->UseDefaultCredentials = false; 
     client->Credentials = gcnew System::Net::NetworkCredential(from, pwd); 
     client->Port = 587; 
     client->Host = "smtp.gmail.com"; 
     client->EnableSsl = true; 
     MailMessage ^mail = gcnew MailMessage(from, to); 
     mail->Subject = subjectStr; 
     mail->Body = messageStr; 
     try 
     { 
      client->Send(mail); 
     } 
     catch (Exception ^ex) 
     { 
      Console::WriteLine("Message : " + ex->Message); 
      return 1; 
     } 

     Console::WriteLine("Message : Done"); 
     return 0; 
} 
+2

你需要擺脫使用強制使編譯器停止告訴你,你這樣做是不對的習慣。 (LPCWSTR)只會阻止編譯器抱怨,它並不會阻止你做錯了。你用L前綴一個字符串文字,使其成爲一個寬字符串,如L「這是一個寬字符串」。使用LoadLibrary()也是錯誤的,您可以使用Assembly :: LoadFrom()來加載託管程序集。沒有什麼意義,只需添加對程序集的引用,以便CLR自動爲您加載DLL。 –

+0

@HansPassant他正在測試他的導出函數入口點。 –

+0

謝謝漢斯和湯姆! – Suvesh

回答

2

當Win32 API函數失敗時,它通常會爲該線程設置一個錯誤代碼。所以,說這個函數返回NULL是不夠的。 LoadLibrary文檔指向GetLastError文檔。

這可能是出了什麼問題:

LoadLibrary((LPCWSTR)"pathto\\email.dll"); 

你不能施放更改文件路徑的字符串的表示。你似乎已經定義了UNICODE,這很好;您最終將調用LoadLibraryW而不是LoadLibraryA。要構建LoadLibraryW文件路徑,使用方法:

LoadLibraryW(L"pathto\\email.dll"); 
+0

同意;謝謝。理想情況下,我們會使用'u'pathto \\ email.dll「,因爲這正是LoadLibraryW所要求的。但今天不支持。 –

+0

非常感謝它爲我工作!我現在可以通過在dllMain中圍繞dllMain進行一次更改來調用導出的函數,使用#pragma unmanaged和#pragma進行管理,因爲測試項目是使用w/o clr構建的。 – Suvesh