0

i have an old DLL written in VisualBasic and need to call the functions in C#. 14 of the 15 functions a already running (Tested with console project). The remaining function has a paramater PChar where i dont know how to call it in C#.

A working function looks like this:

[DllImport("C:\\DLL\\visualbasic.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern int command(out UInt32 pNumber);

public void Executecommand(out UInt32 pNumber, out int Res)
{
Res = command(out pNumber);
}

The not working function has two parameters: 1. out pData: PChar 2. const pDataLen (This is the length of data that is returned)

The manual for the VB DLL says that it is important to reserve memory before calling the function and also to free up memory after function is finished. 20 characters should be enough.

Can someone give me a hint how to call the function? When i simply use "string" then i get an exeception: An unhandled exception of Type System.AccesViolationException occured. Addidtional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Thanks for help.

Thomas Mann
  • 99
  • 3
  • 19
  • 1
    That's a very unhelpful snippet. PChar is a Delphi type, "out" and "const" make no sense. Most likely correct argument type is StringBuilder, no ref or out, with CharSet.Ansi. Set its Capacity to 20 before the call. Second argument is surely int but hard to guess if it needs ref. – Hans Passant Sep 27 '16 at 09:36
  • I tried with stringbuilder. If i dont use the "out" then the function executes but i have no data in the stringbuilder variable. If i use the out parameter at tthe stringbuilder-variable then i have the same error as in first posting. public void NotWorking(out string pData, int pDataLen, out int Res) { StringBuilder MyStringBuilder = new StringBuilder("", 20); Res = Execute_NotWorking(MyStringBuilder, pDataLen) pData= MyStringBuilder.ToString(); } – Thomas Mann Sep 27 '16 at 11:25

2 Answers2

0

Did you try with pointer??

public static extern void NotWorkFunction(out IntPtr pOut, int someConst)

void Main(string[] args)
{
  IntPtr pOut;
  int dataLength;
  string foo;

  NotWorkFunction(pOut, dataLength);
  foo = Marshal.PtrToStringAuto(pOut);
  BlockFree(pOut);
}
Ar Aui
  • 392
  • 1
  • 7
  • 17
-1

The solution was to use "ref string" instead of "out string".

Thomas Mann
  • 99
  • 3
  • 19