user4604440
user4604440

Reputation:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt DllImport

I've created a dll in c++. I've a function in that dll which contains the following code.

__declspec(dllexport) void MyFunction(CString strPath)
{
    BYTE startBuffer[] = { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0 };
    FILE *f = _wfopen(strPath.GetBuffer(strPath.GetLength()), _T("wb"));        
    if (f != NULL)
    {
        strPath.ReleaseBuffer();
        fwrite(startBuffer, sizeof(startBuffer), 1, f);
        fclose(f);
    }
}

If I comment this line and then call the dll. It won't be any problem.

The calling convention is as follows :

[DllImport("OutExt.dll",CharSet=CharSet.Unicode)]
static extern void MyFunction([MarshalAs(UnmanagedType.LPStr)] string strPath);

someone please help me out for this problem.

Upvotes: 1

Views: 556

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

CString is a native C++ class that cannot be marshalled using p/invoke. You will need to use a pointer null-terminated character array.

Either:

__declspec(dllexport) void MyFunction(const char *strPath)

if you must restrict yourself to the legacy ANSI code page, or

__declspec(dllexport) void MyFunction(const wchar_t *strPath)

for Unicode.

On the C# side the declarations would be:

[DllImport("OutExt.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern void MyFunction(string strPath);

and

[DllImport("OutExt.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
static extern void MyFunction(string strPath);

respectively.

Upvotes: 2

Related Questions