繁体   English   中英

将指针从C#传递到C ++

[英]Passing pointer from C# to C++

我正在尝试从C#(作为short [])到C ++(作为无符号short *)传递2D掩码(全为0,期望感兴趣的区域为1s),但是我无法在C ++中获得正确的值。

C#

[DllImport("StatsManager.dll", EntryPoint = "SetStatsMask")]
private static extern int SetStatsMask(IntPtr mask, int imgWidth, int imgHeight);

short[] mask;
mask = new short[8*8];
// some operation here making a ROI in mask all 1.  ex 0000111100000000 in 1D 
IntPtr maskPtr = Marshal.AllocHGlobal(2 * mask.Length);
Marshal.Copy(mask, 0, maskPtr, mask.Length);
SetStatsMask(maskPtr, width, height);

C ++

long StatsManager::SetStatsMask(unsigned short *mask, long width, long height)
{
    //create memory to store the incoming mask
    //memcpy the mask to the new buffer 
    //pMask = realloc(pMask,width*height*sizeof(unsigned short));

    long ret = TRUE;

    if (NULL == _pMask)
    {
        _pMask = new unsigned short[width * height];
    }
    else
    {
        realloc(_pMask,width*height*sizeof(unsigned short));
    }

    memcpy(mask,_pMask,width*height*sizeof(unsigned short));

    SaveBuffer(_pMask,  width,  height);

    return ret;
}

但是我在使用观察窗口的C ++中可以看到的掩码是52536而不是0000111100000000 ,所以我想知道我在哪里搞砸了? 有人可以帮忙吗? 谢谢。

我相信您放错了memcpy的参数:

memcpy(mask,_pMask,width*height*sizeof(unsigned short));

据我了解,您想从mask复制到_pMask ,因此您应该编写:

memcpy(_pMask, mask, width*height*sizeof(unsigned short));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM