C#P/调用数据类型转换 [英] C# P/Invoke Data Types Convertion

查看:74
本文介绍了C#P/调用数据类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人

我在p/invoke中有一个小问题:
我在C ++中的函数签名就是这样的东西

every body

i have a little problem in p/invoke :
my function signature in c++ is some thing like this

ReadData (char* data);



我将字符串的地址传递给该函数,并且我的数据将被填充到该地址中(函数工作正常,但只是数据封送处理出错并导致错误),现在我想在.net数据类型的C#女巫类型中使用它必须使用
正常工作

我在C#中使用了此功能,但发生了错误.



that i will pass address of string to that fucntion and my data will be filled in the address (function works fine but just data marshaling goes wrong and cause in error), now i want to used it in C# witch type of .net data type must be used
to properly working

i used this in C# but error happend.

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int ReadData (out String data);

IntPtr readAddrs = NativeSupport.GetProcAddress(dll, "ReadData");
            ReadData read = (MS_Read)Marshal.GetDelegateForFunctionPointer(readAddrs, typeof(ReadData));

string d = "";
read(out d);
//Attempted to read or write protected memory. This is often an indication that //other memory is corrupt. 




必须使用哪种封送处理.




what kind of marshaling must be used.
tanks in advance .

推荐答案

不要使用字符串-它们是不可变的(即,它们不能更改).请改用StringBuilder,并将其初始大小设置为例程期望返回的最大大小,我怀疑它应该是ref参数而不是out.没有看到代码,我却无法分辨.如果ReadData不会修改它,则可以将它作为不带outref的参数传递就可以了.
Don''t use a string - they are immutable (i.e. they cannot be changed). Use a StringBuilder instead and set it''s initial size to the maximum your routine expects to return, and I suspect that it should be a ref parameter rather than an out. Without seeing the code, I can''t tell though. It may be that just handing it through as a parameter without out or ref will work fine, if ReadData does not modify it.


这篇关于C#P/调用数据类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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