C# 从cpp到csharp的DllImport;生成但在运行时卡在cpp函数中
代码正在生成,没有错误,但当我运行它时,它被卡在从csharp中的DllImport调用的函数中。我使用Debug.WriteLine()跟踪了这一点,以确认代码被卡住的位置 csharp项目中的DllImport管线:C# 从cpp到csharp的DllImport;生成但在运行时卡在cpp函数中,c#,c++,interop,uwp-xaml,dllimport,C#,C++,Interop,Uwp Xaml,Dllimport,代码正在生成,没有错误,但当我运行它时,它被卡在从csharp中的DllImport调用的函数中。我使用Debug.WriteLine()跟踪了这一点,以确认代码被卡住的位置 csharp项目中的DllImport管线: [DllImport("GettingData.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] static unsafe extern bool Generat
[DllImport("GettingData.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
static unsafe extern bool GenerateItems(out ItemsSafeHandle itemsHandle,
out double* items, out int itemCount);
[DllImport("GettingData.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
static unsafe extern bool ReleaseItems(IntPtr itemsHandle);
cpp项目中的dllexport代码如下所示。请注意,由于生成错误,代码使用头文件和cpp,其中cpp项目中定义的函数“已经”在App.xaml.h中定义。为了解决这个问题,类在头文件中定义,成员函数定义在cpp文件中
#define EXPORT extern "C" __declspec(dllexport)
typedef intptr_t ItemListHandle;
EXPORT bool GenerateItems(ItemListHandle* hItems, double** itemsFound, int* itemCount)
{
auto items = new std::vector<double>();
for (int i = 0; i < 500; i++)
{
items->push_back((double)i);
}
*hItems = reinterpret_cast<ItemListHandle>(items);
*itemsFound = items->data();
*itemCount = items->size();
return true;
}
EXPORT bool ReleaseItems(ItemListHandle hItems)
{
auto items = reinterpret_cast<std::vector<double>*>(hItems);
delete items;
return true;
}
EXPORT bool GenerateItems(ItemListHandle*hItems,double**itemsFound,int*itemCount)
{
自动项目=新标准::向量();
对于(int i=0;i<500;i++)
{
项目->推回((双)i);
}
*hItems=重新解释铸造(项目);
*itemsFound=项目->数据();
*itemCount=项目->大小();
返回true;
}
导出bool ReleaseItems(ItemListHandle hItems)
{
自动项目=重新解释施法(hItems);
删除项目;
返回true;
}
我正在跟踪对这篇文章的投票结果,以获得所需的最低代码。由于我正在UWP解决方案中运行此程序,因此无法将C++/CLI包装器作为此解决方案的另一个项目使用。“我使用Debug.WriteLine()跟踪了此过程”-future提示;只需使用调试器。所有变量都在C和C++之间的堆栈上传递。当你从C++代码返回时,除了下面的条件1之外,所有的项都丢失了)在C++中调用对象之前的内存被分配在C++代码中,内存分配是使用Windows分配的,所以内存可以从C 3访问,值是C++的返回值。返回值放在Micropolicessor AX寄存器中,因此不在堆栈上。要调试此类问题,最好的选择是不要忘记在C#projet中调试下的项目属性中选中“启用本机代码调试”。然后使用Debug Tab.hmm在所有异常上启用断点。我没有在本说明中显示的选项,我相信您指的是@NPE。链接给出了正确的步骤。这些选项只能在C++项目中而不是C++中使用。如果您没有该选项,请尝试转到Debug-Exceptions(Ctrl+D,E)并选择在抛出或用户未处理异常时中断。