Click here to Skip to main content
15,848,930 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi I have written a code in C# to load functions in an unmanaged dll.
This is the code.
class Program
     static unsafe void Main(string[] args)
         int deviceNr;
         char* Info;
         int intMyReturnVal;
         deviceNr = 0;
         Info = null;
         intMyReturnVal = sample_getinfo(deviceNr, Info);

     private unsafe static extern int sample_getinfo(int deviceNr, char* Info);

and this is the API function description by dll supllier.

1. Sample_GetInfo

Sample_GetInfo (int deviceNr,
char* Info);

deviceNr is a number of found card in system
Info is handler for string with information about current card in system

Returns 0 (zero) when success. Otherwise return an error code.

This function provide information about installed card in system. Information returned
in Info string looks like below:
„SN YY.SN rev. RRR", where:
YY – year of production
SN – serial number
RRR – firmware revision

The problem is that when I run this code I get the bellow error exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I have written this in to and get the same result.
I would appreciate your help.

As elaborated by SA you are passing null to sample_getinfo that caused the error. A quick solution to allocate memory to this pointer.

change this line

char* Info;

to this

char* Info = new char[255];

and try again.
Share this answer
Richard MacCutchan 9-Jul-13 3:51am    
Did you miss a new directive?
_Asif_ 9-Jul-13 4:03am    
Yes actually i did miss that. Thanks for pointing it out.
Nooredin 9-Jul-13 4:37am    
thank you dear friend
Nooredin 9-Jul-13 16:39pm    
it gives this exception
cannot implicitly convert from char[] to char*
First of all, char* info, by your native function signature, is supposed to be input parameter. Or it can return a character via a pointer. By default, input char* parameter is marshaled as System.String parameter. And you are passing null. You cannot return anything.

Share this answer
Nooredin 9-Jul-13 4:37am    
thanks. i will check it soon
Sergey Alexandrovich Kryukov 9-Jul-13 10:18am    
You are welcome...
Nooredin 9-Jul-13 16:39pm    
it gives this exception
cannot implicitly convert from char[] to char*
Sergey Alexandrovich Kryukov 9-Jul-13 17:30pm    
What code? Your code is incorrect in principle, I tried to explain where. You need to decide how parameters are passed...
Nooredin 10-Jul-13 0:39am    
I just added this line to code as you mentioned.

Info = new char[255];

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900