I want to export a C++ class, which has a member std::vector<int>
. How to export this class so that my C# application can consume it? And how to write the corresponding .Net code?
This is what I tried so far, following the examples g开发者_Go百科iven here.
#include <vector>
# define BOOSTGRAPH_API __declspec(dllexport)
# define EXPIMP_TEMPLATE
EXPIMP_TEMPLATE template class BOOSTGRAPH_API std::vector<int>;
class BOOSTGRAPH_API MyClass
{
public:
std::vector<int> VectorOfInts;
public:
bool operator < (const MyClass c) const
{
return VectorOfInts < c. VectorOfInts;
}
bool operator == (const MyClass c) const
{
return VectorOfInts == c. VectorOfInts;
}
};
But then I'm stucked.
What are you trying to do? I see BOOST_GRAPH_API, what are you up to? You will not be able to use native C++ code from .Net directly, neither you should! That would force you to compile all imported dependencies on C++ standard library and boost(!) with clr support...
You need to define interfaces to your classes along with proper factory methods. These can be safely exported and wrapped by C++/CLI objects which you can directly reference within .Net programs:
// imyclass.h
__declspec( dllexport )
IMyClass* CreateInstance();
__declspec( dllexport )
class IMyClass {
public:
virtual int CompareTo(IMyClass*) = 0;
virtual ~IMyClass() {}
};
// myclass.h
#include "imyclass.h"
#include <vector>
class MyClass : public IMyClass {
std::vector<int> mIntVector;
public:
virtual int CompareTo(IMyClass*);
// constructors and access functions go here...
};
// myclass.cpp
#include "myclass.h"
#include <memory>
IMyClass* CreateInstance() {
return new MyClass;
}
// implementations of whatever MyClass should do go here...
Observe that only the interface IMyClass
and its creator is exported by the dll, nothing else. In a C++/CLI project, you define a C++/CLI disposable wrapper which holds a pointer to IMyClass
and imports only imyclass.h. The wrapper which imprt only IMyClass
and it's creator should be similar to something shown below, but take care to get the finalizer semantics right, not sure at the moment what is generated autmatically by the compiler...:
ref class IMyClassWrapper {
IMyClass* mPtrResource;
public:
int CompareTo(IMyClassWrapper^ pOther) {
return this->mPtrResource->CompareTo(pOther->mPtrResource);
}
IMyClassWrapper() {
mPtrResource = ::CreateInstance();
}
~IMyClassWrapper() {
this->!IMyClassWrapper();
}
protected:
!IMyClassWrapper() {
delete mPtrResource;
mPtrResource = 0;
}
};
C# can't understand __declspec(dllimport), it can only grok C-style interfaces. You will have to go through C++/CLI, they offer STL->.NET conversions, IIRC.
精彩评论