如何在C#中编组int *?

时间:2010-04-28 20:38:57

标签: .net marshalling intptr

我想在非托管库中调用此方法:

void __stdcall GetConstraints(

  unsigned int* puiMaxWidth,

  unsigned int* puiMaxHeight,

  unsigned int* puiMaxBoxes

);

我的解决方案:

  • 代表定义:

    [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetConstraintsDel(UIntPtr puiMaxWidth,UIntPtr puiMaxHeight,UIntPtr puiMaxBoxes);

  • 方法的调用:

    // PLUGIN NAME
    GetConstraintsDel getConstraints = (GetConstraintsDel)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(GetConstraintsDel));
    
     uint maxWidth, maxHeight, maxBoxes;
    
     unsafe
     {
        UIntPtr a = new UIntPtr(&maxWidth);
        UIntPtr b = new UIntPtr(&maxHeight);
        UIntPtr c = new UIntPtr(&maxBoxes);
        getConstraints(a, b, c);
     }
    

它有效,但我必须允许“不安全”的标志。有没有不安全代码的解决方案?或者这个解决方案好吗?我不太明白用不安全标志设置项目的含义。

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

刚出来?

即:

HRESULT GetTypeDefProps (
   [in]  mdTypeDef   td,
   [out] LPWSTR      szTypeDef,
   [in]  ULONG       cchTypeDef,
   [out] ULONG       *pchTypeDef,
   [out] DWORD       *pdwTypeDefFlags,
   [out] mdToken     *ptkExtends
);

可以正常使用:

uint GetTypeDefProps
(
  uint td, 
  [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)]char[] szTypeDef, 
  uint cchTypeDef, 
  out uint pchTypeDef, 
  out uint pdwTypeDefFlags, 
  out uint ptknds
 );

样品使用;

char[] SzTypeDef;
uint CchTypeDef;
uint PchMember;
IntPtr PpvSigBlob;
uint PbSigBlob;

  SzTypeDef= new char[500];
  CchTypeDef= (uint)SzTypeDef.Length;

ResPT= 
  MetaDataImport.GetTypeDefProps
  (
    td, 
    SzTypeDef, 
    CchTypeDef, 
    out pchTypeDef, 
    out pdwTypeDefFlags,
    out ptkExtends
  );