Calling C++ dll from C#: Attempted to read or write protected memory
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Calling C++ dll from C#: Attempted to read or write protected memory

  1. #1
    Join Date
    Apr 2003
    Posts
    99

    Thumbs down 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

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,359

    Re: Calling C++ dll from C#: Attempted to read or write protected memory

    Quote Originally Posted by zvivered View Post
    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.

  3. #3
    Join Date
    Apr 2003
    Posts
    99

    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center