dll:
extern "C"
{
__declspec(dllexport) void PrintVector(const vector<int> v)
{
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
}
}
exe:
typedef void (* FUNC)(const vector<int>);
int main()
{
HMODULE hModule = LoadLibrary("VectorDll.dll");
if (hModule)
{
FUNC fun = (FUNC)GetProcAddress(hModule, "PrintVector");
vector<int> v(10, 1);
fun(v);
}
return 0;
}
上面代碼存在嚴重的問題,運行時會崩潰:

在windows核心編程中明確的說了在dll中如果申請了內存空間,就一定要在dll中釋放這塊內存空間。
在exe和dll都靜態鏈接到C/C++運行時庫的時候,exe和dll都有各自的堆(heap)空間,所以各自申請的內存需要各自釋放。
上面代碼將參數改成 const vector<int> & 就可以正常運行。
但是如果exe中的vector版本和dll中vector的版本不同,問題又會出現,并且這些是未知的問題。
所以在dll函數接口中盡量使用基本數據類型。
關于exe和dll內存分配:
http://www.codeguru.com/forum/showthread.php?t=229394
http://www.gamedev.net/community/forums/topic.asp?topic_id=289896
http://blog.csdn.net/dotphoenix/archive/2009/07/14/4348686.aspx
http://blog.sina.com.cn/s/blog_60d705b10100g4ou.html
http://hi.baidu.com/honey%BC%A6/blog/item/8780d1f918976ed5b58f310f.html
關于dll和template/STL:
http://support.microsoft.com/default.aspx?scid=KB;en-us;q172396
http://support.microsoft.com/default.aspx?scid=KB;en-us;q168958
http://www.hellocpp.net/Articles/Article/714.aspx