• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7580
  • Last Modified:

Attempted to read or write protected memory. Then calling function from external API (dll)

I'm using an dll and have declared some functions that I need to use:
Declare Function API_GetSeg Lib "MLAPI32.dll" (ByVal strSeg As String, ByVal Level As Integer, ByVal Threshold As Integer) As <MarshalAs(UnmanagedType.U1)> Boolean
Declare Function API_GetElm Lib "MLAPI32.dll" (ByVal strSegment As String, ByVal strElement As String, ByRef rData As String) As <MarshalAs(UnmanagedType.U1)> Boolean

The first function works fine (API_GetSeg).
I've got problems with the second function (API_GetElm) that gives the following error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

API_GetElm,  Variable rData is declared with ByRef because the function is going to change this value/return a string.

When I'm running the code with rData declared with ByVal, the error does not appear, but then I don't get my return value.

I think the dll is written in C.

How should I declare the function?

Please help.
1 Solution
Please show unmanaged C function declaration.
Hello, trulseri,

I'm sorry that I don't know anything about the API you are calling.  Do you have any documantation for it?  With many calls to C functions it is typically necessary to preallocate the buffer before the call.  For example, if the call will return a maximum of 256 characters you need to pass in a buffer large enough to receive 256 characters.  Have you tried something like:

    Dim rDataBuffer As New String(" "c, 256)
    booResult = API_GetElm(..., rDataBuffer)

where you are passing rDataBuffer ByVal?  (Of course, you have to know how large a string to allocate.  256 characters is just intended to be an example.)


Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now