我創建了一個帶有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;
}
你需要擺脫使用強制使編譯器停止告訴你,你這樣做是不對的習慣。 (LPCWSTR)只會阻止編譯器抱怨,它並不會阻止你做錯了。你用L前綴一個字符串文字,使其成爲一個寬字符串,如L「這是一個寬字符串」。使用LoadLibrary()也是錯誤的,您可以使用Assembly :: LoadFrom()來加載託管程序集。沒有什麼意義,只需添加對程序集的引用,以便CLR自動爲您加載DLL。 –
@HansPassant他正在測試他的導出函數入口點。 –
謝謝漢斯和湯姆! – Suvesh