有什麼方法可以使用不同編譯器構建的C++ dll兼容嗎?這些類可以有創建和銷燬的工廠方法,因此每個編譯器都可以使用它自己的新/刪除(因爲不同的運行時有自己的堆)。編譯器之間的Dll兼容性
我嘗試以下的代碼,但它碰撞在所述第一構件的方法:
interface.h
#pragma once
class IRefCounted
{
public:
virtual ~IRefCounted(){}
virtual void AddRef()=0;
virtual void Release()=0;
};
class IClass : public IRefCounted
{
public:
virtual ~IClass(){}
virtual void PrintSomething()=0;
};
TEST.CPP與VC9編譯,TEST.EXE
#include "interface.h"
#include <iostream>
#include <windows.h>
int main()
{
HMODULE dll;
IClass* (*method)(void);
IClass *dllclass;
std::cout << "Loading a.dll\n";
dll = LoadLibraryW(L"a.dll");
method = (IClass* (*)(void))GetProcAddress(dll, "CreateClass");
dllclass = method();//works
dllclass->PrintSomething();//crash: Access violation writing location 0x00000004
dllclass->Release();
FreeLibrary(dll);
std::cout << "Done, press enter to exit." << std::endl;
std::cin.get();
return 0;
}
一個.cpp用g ++編譯 g ++ .exe -shared c.cpp -o c.dll
#include "interface.h"
#include <iostream>
class A : public IClass
{
unsigned refCnt;
public:
A():refCnt(1){}
virtual ~A()
{
if(refCnt)throw "Object deleted while refCnt non-zero!";
std::cout << "Bye from A.\n";
}
virtual void AddRef()
{
++refCnt;
}
virtual void Release()
{
if(!--refCnt)
delete this;
}
virtual void PrintSomething()
{
std::cout << "Hello World from A!" << std::endl;
}
};
extern "C" __declspec(dllexport) IClass* CreateClass()
{
return new A();
}
編輯: 我在GCC CreateClass方法中添加了下面一行,文本被正確地打印到控制檯,所以它的defenatly函數調用多數民衆贊成在殺死它。
std::cout << "C.DLL Create Class" << std::endl;
我想知道,如何COM勉強維持二進制兼容性,甚至跨越語言,因爲它的basicly與所有的繼承類(雖然只是單),因此虛函數。只要我能夠維持基本的面向對象的東西(即類和單一繼承),如果我不能重載操作符/函數,我就不會受到大規模的困擾。
COM如何做到這一點?使用輕量級RPC調用 - 您可以使用dce-rpc構建您的應用程序,並獲得相同的結果。在任何情況下,COM都不會提供指向外部dll內存的指針,它會對該dll進行函數調用。 – gbjbaanb 2009-01-14 13:43:07
以下文章[此處](http://eli.thegreenplace.net/2011/09/16/exporting-c-classes-from-a-dll/),[here](http://www.codeproject。 com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#CppMatureApproach)和[here](http://chadaustin.me/cppinterface.html)可能會有所幫助。除了內聯的虛擬析構函數之外,你的代碼示例幾乎就在那裏。 AFAIK,抽象接口中的所有方法都必須是純虛擬的'= 0'。 – greatwolf 2013-03-12 22:46:11