簡體   English   中英

C#/ C ++互操作和由C ++分配的數組

[英]c# / c++ interop and out allocated array by c++

我在dll中有一個第三方c ++方法,如下所示:

void GetValues(int *pCount, int **ppValues);

c ++的用法是:

int count = 0, *pValues = NULL;
GetValues(&count, &pValues);
CoTaskMemFree(pValues);

我想在c#中調用此方法:它聲明為:

void GetValues([out] int pCount, IntPtr ppValues);

c#用法(使用此代碼的方法被標記為不安全):

   int *pValues = null;
    try
    {
       int count;
       GetValues(out count, new IntPtr(&pValues));
       for (var i=0; i<count; i++)
       {
           var val = pValues[i];
       }
    }
    finally
    {
       Marshal.FreeCoTaskMem(new IntPtr(pValues));
    }

這似乎可行。 但是我想知道這是否正確,或者我沒有看到這種方法是否有問題。

編輯:從無效GetValues([out] int pCount,[out] IntPtr ppValues)更改了c#聲明; 使GetValues([out] int pCount,IntPtr ppValues)無效;

也許我丟失了一些東西,但是調用GetValues(out count, new IntPtr(&pValues));缺少了“ out”前綴GetValues(out count, new IntPtr(&pValues));

我將更簡單地解決此問題:

        unsafe void test()
    {
        IntPtr intPtr = IntPtr.Zero;
        try
        {
            int count = 0;
            GetValues(out count, out intPtr);

            int* pValues = (int*)intPtr;

            for (var i = 0; i < count; i++)
            {
                var val = pValues[i];
            }
        }
        finally
        {
            Marshal.FreeCoTaskMem(intPtr);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM