Problems with a DLL

hello all,

I've been receiving an AccessViolationException whenever trying to pass a couple of parametres inside a function placed in an external DLL:
public partial class soldsk
{
[DllImport("C:\\...myProject\\\\bin\\Debug\\myDLL32.dll",
EntryPoint="sendtram")]
public static extern int SC_sendtram(int hwnd, int port, int pasdereponse,
int vto, string Commande, ref string Reponse);
}
... //some code
Ret = (short)soldsk.SC_sendtram(hwnd, port, 0, 0, command, ref rep)

(when command and rep are strings of a fixed length)

Obviously, when I leave out the 'ref' keyword, it all goes smoothly, but the parameter
rep is not affected by the DLL method (who normally gives it a new value).

Hope this was clear enough- if not just let me know.
I'll be more than grateful for any idea..

PS- I nearly forgot to add that on VB.NET the similar code works without a problem! In fact, in vb I have called the DLL method with ByVal parameters, still the method gives rep a new value.



Answer this question

Problems with a DLL

  • tirupati_mullick

    Searching for answers, I came across the System.Runtime.InteropServices.Marshall class which might be useful here, still am having some difficulties. I've tried to work with a string pointer:

    public static extern int SC_sendtram(int hwnd, int port, int pasdereponse, int vto, string Commande, ref string* Reponse);
    //...
    short Ret;
    string rep = new string(Strings.Chr(0), 256);
    string* Rep = (string*)Marshal.StringToHGlobalAuto(rep).ToPointer();
    Ret = (short)soldsk.SC_sendtram(hwnd, port, 0, 0, command, ref rep);

    but the compiler tells me 'Pointers and fixed size buffers may only be used in an unsafe context'.
    Anyone


  • Scott Sheppard

    Try replacing ref string with StringBuilder. The string class is immutable meaning it cannot be changed once created, therefore is no good to receive a string from your DLL function. I think that the outputted string will be marshalled automatically into the StringBuilder.
  • gokhanmutlu

    Thanks for the answer.

    It turns out that passing a byte array does the trick- no marshaling or pointers. I'll just have to convert the array afterwards back into a string. Still it's weird that on vb it works just fine with a string...


  • Problems with a DLL