-
July 17th, 2013, 03:31 PM
#1
Calling C++ dll from C#: Attempted to read or write protected memory
Hello,
From a C# console application I'm trying to call a constructor + methd of a C++ class.
The P/invoke is:
[DllImport("MyClass.dll", EntryPoint = "?Set@CMyClass@@QAEXH@Z")]
static extern void Set_dll(int x);
[DllImport("MyClass.dll", EntryPoint = "??0CMyClass@@QAE@XZ")]
static extern void MyClass_dll();
public MyClass()
{
MyClass_dll();
}
public void Set(int x)
{
Set_dll(x);
}
The C++ class is:
#ifdef MYCLASS_EXPORTS
#define MYCLASS_API __declspec(dllexport)
#else
#define MYCLASS_API __declspec(dllimport)
#endif
class MYCLASS_API CMyClass {
private:
int m_a;
public:
CMyClass(void){m_a = 0;};
// TODO: add your methods here.
void Set (int x){m_a = x;};
};
When the C# code reaches the C++ constructor I'm getting an exception on the line: m_a=0.
It seems m_a has no address yet.
If CMyClass does not contain any attributes, calling the method from C# works fine.
What am I doing wrong ?
Thanks,
Zvika
-
July 18th, 2013, 08:06 PM
#2
Re: Calling C++ dll from C#: Attempted to read or write protected memory
Originally Posted by zvivered
What am I doing wrong ?
You can't pinvoke to C++ methods only to C style methods. Internally inside your dll, you can use class (or classes) to manage the work, but you must only export regular functions.
-
July 18th, 2013, 11:34 PM
#3
Re: Calling C++ dll from C#: Attempted to read or write protected memory
When a class has attributes it's methods can not be called from C# using P/invoke. With P/invoke, no object is created so no memory is allocated.
The C++ class must be wrapped with C++/CLI class linked into a dll.
This dll will be added as a reference to the C# application.
Thanks,
Zvika
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|