C#调用非托管函数参数为Void* 时,方法

Void Sample

This sample demonstrates how to pass data to an unmanaged function that expects a void pointer as an argument. The sample provides two solutions.

The Void sample uses the following unmanaged function, shown with its original function declaration:

PinvokeLib.dll is a custom unmanaged library that contains an implementation for the previously listed function.

In this sample, the LibWrap class contains an enumeration of types and two managed prototype methods: SetData and SetData2. These methods represent the following approaches for passing data to an unmanaged function expecting a void*:

  • SetData declares the DataType enumeration and an object. The MarshalAsAttribute attribute sets the UnmanagedType enumeration to AsAny, which determines the type of an object at run time and marshals the object as that type.

  • SetData2 overloads the method to declare the DataType enumeration and to identify a double or string type. The ref ( ByRef in Visual Basic) keyword passes the double by reference.

The App class calls the methods and initializes the enumeration elements. The first approach specifies each enumeration element; the second approach specifies only the largest value type and the string.

Declaring Prototypes
VB
C#
C++
F#
JScript
public class LibWrap
{
   public enum DataType 
   {
      DT_I2 = 1,
      DT_I4,
      DT_R4,
      DT_R8,
      DT_STR
   }
   
   // Uses AsAny when void* is expected.
   [ DllImport( "..\\LIB\\PinvokeLib.dll" )]
   public static extern void SetData( DataType t, 
      [ MarshalAs( UnmanagedType.AsAny )] Object o );
   // Uses overloading when void* is expected.
   [ DllImport( "..\\LIB\\PinvokeLib.dll", EntryPoint="SetData" )]
   public static extern void SetData2( DataType t, ref double i );
   [ DllImport( "..\\LIB\\PinvokeLib.dll", EntryPoint="SetData" )]
   public static extern void SetData2( DataType t, String s );   
}
Calling Functions
VB
C#
C++
F#
JScript
public class App
{
   public static void Main()
   {
      Console.WriteLine( "Calling SetData using AsAny... \n" );
      LibWrap.SetData( LibWrap.DataType.DT_I2, (short)12 );
      LibWrap.SetData( LibWrap.DataType.DT_I4, (long)12 );
      LibWrap.SetData( LibWrap.DataType.DT_R4, (float)12 );
      LibWrap.SetData( LibWrap.DataType.DT_R8, (double)12 );
      LibWrap.SetData( LibWrap.DataType.DT_STR, "abcd" );
      
      Console.WriteLine( "\nCalling SetData using overloading... \n" );   
      double d = 12;
      LibWrap.SetData2( LibWrap.DataType.DT_R8, ref d );
      LibWrap.SetData2( LibWrap.DataType.DT_STR, "abcd" );
   }
}
See Also
Concepts
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值