As msdn http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx says “Platform Invocation Services (PInvoke) allows managed code to call unmanaged functions that are implemented in a DLL.”
I want to import some class from DLL that i made in c++
Is it possible and how?
for example, i have some structures inside DLL:
struct __declspec(dllexport) DLLVector3
{
float x, y, z;
};
struct __declspec(dllexport) DLLQuaternion
{
float x, y, z, w;
};
class __declspec(dllexport) DLLCharacter
{
public:
DLLVector3 position;
DLLQuaternion orientation;
DLLCharacter()
{
}
~DLLCharacter()
{
}
void setPosition(PxVec3 pos)
{
position.x = pos.x;
position.y = pos.y;
position.z = pos.z;
}
void setOrientation(PxQuat or)
{
orientation.x = or.x;
orientation.y = or.y;
orientation.z = or.z;
orientation.w = or.w;
}
};
struct __declspec(dllexport) PhysicalObject
{
DLLCharacter *character;
PxRigidActor *mActor;
PxController *mController;
};
Which way i can import those? Especially those structures with pointers
You don’t need to write C++ managed code for access – but – you can’t easily hop around between unmanaged and managed memory. Here’s a few key points
1) Use [StructLayout(LayoutKind.Sequential)] to define .net classes that map on top of your c++ structs
2) Basic types like doubles, int32, etc move across the P/Invoke layer efficiently – more complex types earn you the .net variant of thunking – msft doco covers which data types move efficiently, try and use them
3) Everything that’s a pointer in C++ land is an IntPtr in .net land and if you want to be safe you should treat it as a handle, i.e. you get the c++ side to do any manipulations/access to the underlying structure
4) Access to the native C++ is pretty straightforward (the Handle props are IntPtrs that were originally sourced on the native C++ side)
5) Strings and some other types require marshalling to obtain a .net usable form – note that this happens automatically for strings when you pass a string to unmanaged code, but you have to do it yourself when it’s inbound