哦,C#到底有没有指针的概念啊?我看到网上有很多种说辞,有的说有,要用unsafe,有的说没有。
我也试过用unsafe,如下:
public unsafe struct SISO180006CCUSTOMCMDRESULT
{
...
};
private void btn1_Click(object sender, EventArgs e)
{
unsafe
{
SISO180006CCUSTOMCMDRESULT *pCustomCmdResult;
}
}
但编译老是出现这个错误:error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type
我已经加了unsafe修饰结构体了,不是就把该结构体定义为managed type了吗?
我也试过用unsafe,如下:
public unsafe struct SISO180006CCUSTOMCMDRESULT
{
...
};
private void btn1_Click(object sender, EventArgs e)
{
unsafe
{
SISO180006CCUSTOMCMDRESULT *pCustomCmdResult;
}
}
但编译老是出现这个错误:error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type
我已经加了unsafe修饰结构体了,不是就把该结构体定义为managed type了吗?
解决方案 »
- 关于ExecuteNonQuery()无法执行
- 新手问题,求老鸟
- 抢分:最简单的winform问题
- 关于提示窗口的问题,在C#中像CSDN上面结贴时那样提示窗口是怎么实现的?
- 请问SQL2000如何将'1,2,3,4' 链接其他表得到'AAA,BBB,CCC,DDD'
- SmtpClient发送邮件,附件不在163详细页显示!(公司新人第一次独立做东西,大家帮忙)
- 获取本地文件夹或文件图标没问题。请问如何动态获取FTP服务器上文件夹或文件的图标呢?顶者有分
- 各位大侠请问 C#怎么将汉字转换成16进制啊?
- 我们单位准备采购一台2w左右的web服务器(够奢侈吧)请大家推荐一下。
- C#中我了一个 textbox控件 如何把控件的字符串转化为char[],(按行转换)
- c#地址传参求解
- c#中遇到“尝试读取或写入受保护的内存”错误(100分)
用unsafe是可以显示调用指针的,但不建议这么做
比如,下面的C++代码,在C#中要怎么写 :
void fun1(TStudent **pp)
{
(*p) = malloc(sizeof(TStudent));
...
}
void main()
{
TStudent *p = NULL;
fun1(&p);
free(*p);
*p = NULL;
}
那在C#要写如何写main()函数来调用fun1()啊?
TStudent p = null;
fun1(out p);
关键字对应
in ==> ref
out ==> out个人建议是加一层C++/CLI的封装,方便快捷.
难与不难,看个人,智能提示只是辅助,你可以说的更委婉些.个人觉得,学习难度C++/CLI>C++>C#....
void fun1(TStudent **pp)
{
(*p) = malloc(sizeof(TStudent));
...
}[StructLayout(LayoutKind.Sequential)]
public struct TStudent {
public int age;
}[DllImport(DllName, CharSet = CharSet.Auto, EntryPoint = "fun1")]
static extern void fun(ref Intptr student);//
//使用的时候
//
public TStudent Get(){
int size = Marshal.SizeOf(typeof (TStudent));
IntPtr ptr = Marshal.AllocHGlobal(size);
try
fun(ref Intptr ptr);
}finally {
Marshal.FreeHGlobal(ptr);
}
}
//
//排版不好,会有一些错误,大致思路是这样的^_^
//
可以再请教一个问题吗?我想用到C的共用体union,因此,我改成了这样,但是为什么一运行就会出错呢?
[StructLayout(LayoutKind.Explicit)]
public struct TStudent {
[FieldOffset(0)]
public int age;
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] b1;
}[DllImport(DllName, CharSet = CharSet.Auto, EntryPoint = "fun1")]
static extern void fun(ref Intptr student);//
//使用的时候
//
public TStudent Get(){
int size = Marshal.SizeOf(typeof (TStudent));
IntPtr ptr = Marshal.AllocHGlobal(size);
try
fun(ref Intptr ptr);
}finally {
Marshal.FreeHGlobal(ptr);
}
}
fun(ref IntPtr ptr);