0

I've been having a horrible time for the last couple of days trying to call an unmanaged dll with C#

C++ code

int _stdcall getVBArrayStrValues(LPSTR t, LPSTR iName, short first, short last,
    LPSAFEARRAY FAR * ppsaStringRead)

typedef struct {
    short readStatus;
    LPVOID vbsValueStr;
} vbStringRead;

The existing program called the dll from a VB6 application which initialises the vbsValueStr to be a string 17 characters long char rtnStr[17];. Just before the vbStringRead[] array is passed by reference.
The dll modifies this array to produce the output.

My guess is that I marshal the struct somehow to be be an LPArray. Do I declare the vbsValueStr to be an IntPtr, or Byte[] or char[]?

Every attempt I try I get the error:

Attempt to read or write Protected Memory This is often an indicating that other memory is corrupt

Below is my latest botched attempt.

[DllImport("FILENAME.dll")]
public static extern int getVBArrayStrValues(string t, string iName, int first,
    int last, [MarshalAs(UnmanagedType.LPArray)] ref vbStringRead[] stringRead);


[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct vbStringRead {
    public int readStatus;
    [MarshalAs(UnmanagedType.LPStr)]
    public string valueStr;
}

EDIT:

@Matthew Watson's advice has definitely helped. I'm still struggling with the string component of the struct.

I'm currently trying to declare valueStr as an IntPtr and then marshal it as a char (Sorry not sure if that is the best way to describe it)

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        public struct vbStringRead
        {
            public int readStatus;
            public IntPtr valueStr;
        }

I have tried various ways to set up the the IntPtr so that it is char[17] or byte [17] but it returns the exception "Parameter is incorrect."

5
  • Not a C++ question but a C# pinvoke one. Corrected that for you. Dec 11, 2014 at 12:39
  • Looks like the ppsaStringRead array is a SAFEARRAY - if so, you should be using UnmanagedType.SafeArray instead of UnmanagedType.LPArray Dec 11, 2014 at 12:42
  • That appears to have removed the "Attempt to read or write..." error and is now reporting: "Value cannot be null. Parameter name: ptr". Which is interesting as I don't have a parameter called ptr. I suspect it has to do with the LPVOID.
    – slavs
    Dec 11, 2014 at 13:04
  • Why did you map short to int? Dec 12, 2014 at 7:36
  • Good question, I must have missed that one and will follow that up soon. The existing VB code used int.
    – slavs
    Dec 12, 2014 at 20:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.