invoking native dlls in c#

Hi

I have faced one problem on calling the native dll's functions from C# .Net coding.Actually i wrote

one dll to control the Digital Multimeter in a remote programming mode through GPIB interface.

Initially i have imported the win32 dll provided with GPIB driver in my coding and tried to send the

data to the Digital Multimeter, Whenever i send the data, it throws this Exception

" System.AccessViolationException: Attempted to read or write protected memory. This is often an

indication that other memory is corrupt." , but i will send the data from VC++ application,its

working fine. Is there any specific settings needs to do Please help me to solve this problem.

For your reference i have pasted the header file function ,VC++ coding as well as C# coding here.

Header file function

----------------------------

extern long int _cdecl ieee488_send (long int,char *,unsigned long,long int *);

#define send(addr,s,status) ieee488_send(addr,(char *) (s),0xFFFF,(long int *) status)

VC++

----------

send(temp,info,&status);

info is character pointer

Status - int

C# -- I have tried in the folowing ways

------------------------------------------------------

1. [DllImport("IIEEE_32M")]

public extern static int send(int address,string strCommand , ref int status);

send(inGpibAddress, Command, ref inStatus);

2. [DllImport("IIEEE_32M")]

public extern static int send(int address,string strCommand , out int status);

send(inGpibAddress, Command, out inStatus);

3. [DllImport("IIEEE_32M")]

public extern static int send(int address,[MarshalAs(UnmanagedType.LPStr)] string

strCommand, out int status);

send(inGpibAddress, Command, out inStatus);

4. [DllImport("IIEEE_32M")]

public extern static int send(int address,[MarshalAs(UnmanagedType.LPStr)] string

strCommand, intptr status);

send(inGpibAddress, Command, out intptr inStatus);

Thanks in advance



Answer this question

invoking native dlls in c#

  • GiannaCampbell

    First if you are using a national instruments card, they have a .Net driver on their web site, it saves a ton of time.

    Otherwise you have to "decorate" everything (real important as long has changed length twice!), change strings to char[] and often change pointers (most old strings are just pointers) to ref.

    Example

    [DllImport("My.DLL")] [return: MarshalAs(UnmanagedType.U4)]

    private static extern unsafe uint MyMessage(

    [MarshalAs(UnmanagedType.U4)]uint configval,

    [MarshalAs(UnmanagedType.U2)]ushort cwd1,

    [MarshalAs(UnmanagedType.U2)]ushort cwd2,

    [MarshalAs(UnmanagedType.LPArray)]ref ushort[] data,

    [MarshalAs(UnmanagedType.I4)]int handleval);


  • invoking native dlls in c#