P / Invoke问题 [英] Problem with P/Invoke

查看:118
本文介绍了P / Invoke问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我用C#编写了一个代码来加载非托管dll中的函数。

这是代码。

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);
     }

     [DllImport("opcard2lib.dll")]
     private unsafe static extern int sample_getinfo(int deviceNr, char* Info);
 }





这是dll supllier的API函数说明。



1. Sample_GetInfo



原型:

DLLReturnType

Sample_GetInfo(int deviceNr,

char * Info);



参数:

deviceNr是系统中找到的卡的数量

Info是信息的字符串处理程序关于系统中的当前卡



返回:

成功时返回0(零)。否则返回错误代码。



说明:

此功能提供有关系统中已安装卡的信息。返回的信息
信息字符串中的
如下所示:

SN YY.SN rev。 RRR,其中:

YY - 生产年份

SN - 序列号

RRR - 固件版本



问题是,当我运行此代码时,我得到以下错误异常:

尝试读取或写入受保护的内存。这通常表示其他内存已损坏。



我已经在VB.net中写了这个并得到了相同的结果。

我将非常感谢你的帮助。



and this is the API function description by dll supllier.

1. Sample_GetInfo

Prototype:
DLLReturnType
Sample_GetInfo (int deviceNr,
char* Info);

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

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

Description:
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 VB.net to and get the same result.
I would appreciate your help.

推荐答案

首先, char * info ,通过本机函数签名,应该是输入参数。或者它可以通过指针返回一个字符。默认情况下,输入 char * 参数被编组为 System.String 参数。并且你正在传递null。你不能返回任何东西。



-SA
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.

—SA


由SA详细阐述将null传递给导致错误的sample_getinfo。分配内存的快速解决方案到这个指针。



更改此行



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.


这篇关于P / Invoke问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆