gpt4 book ai didi

c++-cli - 使用 Marshal::GetFunctionPointerForDelegate 并从非托管代码调用回调会导致退出应用程序时缓冲区溢出

转载 作者:行者123 更新时间:2023-12-01 11:44:47 27 4
gpt4 key购买 nike

我正在使用带有 .NET Framework 3.5 的 Visual Studio 2008 并制作一个 C++/CLI/.NET Forms 应用程序;游戏编辑器。除了编辑器之外的所有游戏代码都是纯 C++。我已经到了需要从非托管代码调用表单代码中的回调的地步。

我正在使用 GetFunctionPointerForDelegate。

首先,我的 Form 类中有这些:

public: delegate void ADelegate(Int32, float, float, float, Int32);
public: static ADelegate^ delegateInstance;

然后我在 Form 构造函数中设置回调:

        // Set up World Objects callback
typedef void (__stdcall *WorldLocationUpdateCallback)(Int32, float, float, float, Int32);
WorldLocationUpdateCallback _callback;

// Create an instance of a delegate, using GetFunctionPointerForDelegate
delegateInstance = gcnew ADelegate( this, &MainForm::InitWorldObjectPane );

// Convert the delegate to a pointer
IntPtr anIntPtr = Marshal::GetFunctionPointerForDelegate( delegateInstance );

// Cast the pointer into a function pointer
_callback = static_cast<WorldLocationUpdateCallback>(anIntPtr.ToPointer());

CEditorUI::UI()->setWorldLocationUpdateCallback( (void*)_callback );

所以我存储指针并在非托管代码中,在我的应用程序初始化的早期从不同的线程调用回调:

    // Set up World Object pane in editor to use this map/maptile/etc
{
typedef void (*WorldLocCallback)(int, float, float, float, int);
void* _callback = CEditorUI::UI()->getWorldLocationUpdateCallback();
int _mapId = charGfxObj->getMapId();
float _posX = charGfxObj->getPos().x;
float _posY = charGfxObj->getPos().y;
float _posZ = charGfxObj->getPos().z;
int _tileRadius = TILE_RADIUS;
((WorldLocCallback)(_callback))( _mapId, _posX, _posY, _posZ, _tileRadius );
}

在我关闭应用程序之前,一切都在我的应用程序中完美运行,功能正常。它总是在调用线程中因缓冲区溢出错误而终止,调用堆栈相当无用:

editor.exe!__crt_debugger_hook()    Unknown
>editor.exe!__report_gsfailure() Line 298 + 0x7 bytes C
editor.exe!__CorExeMain@0() + 0xe3 bytes C++

这里的问题在于,即使回调实际上什么都不做,它也会崩溃。要导致崩溃,我所要做的就是启用调用回调的最后一行代码。禁用该行后,没有问题。请记住,崩溃仅在退出时发生,而不是在实际使用回调时发生。

有什么建议可以尝试吗?

最佳答案

在整整一天搞砸并搜索其他相关内容后,我稍微解决了这个问题,以防其他人遇到这个问题。

将委托(delegate)声明移到类之外并用以下方法装饰它:

[UnmanagedFunctionPointerAttribute(CallingConvention::Cdecl)] 

...帮我解决了。显然cdecl的清栈效果解决了溢出问题。

关于c++-cli - 使用 Marshal::GetFunctionPointerForDelegate 并从非托管代码调用回调会导致退出应用程序时缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16272558/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com