从 C# 调试静态库C++

Debugging C++ static lib from C#

本文关键字:C++ 静态 调试      更新时间:2023-10-16

这个问题类似于这个未回答的问题:调试包装在 C++/CLI DLL 中的静态库时,调试器不会单步执行本机代码

设置是相同的。我有一个纯C++静态库,它链接到一个 C++/CLI DLL,然后由 C# 可执行文件使用。根据设置,我可以调试 C# 层,也可以同时调试 C# 和 C++/CLI。无论我尝试什么,我都无法调试C++层。我正在使用Visual Studio 2019。

这是我尝试过的和结果。对于下面描述的所有方案,我在 C++/CLI 和 C++ 函数(而不是 C#(上设置了断点。

  1. 具有本机调试的 C#、具有自动调试功能的 C++ 和 C++/CLI:调试器在 C# 中调用将调用 C++/CLI 函数的调用处停止,但我无法设置它们。Visual Studio 在 C++/CLI 端没有断点的消息(它们处于活动状态,但无法命中(。在C++方面,它说:
This breakpoint will not currently be hit. Breakpoints in module clr.dll are not alowed. This module contains the implementation of the underlying runtime you are trying to debug.
  1. 没有本机调试的 C#,C++和C++/CLI 具有混合调试:C++/CLI 中的断点被命中并处于活动状态。C++断点要么消失,要么显示以下消息:
This breakpoint will not currently be hit. No executable code of the debugger's target code is associated with this line. Possible causes include: conditional compilation, compiler optimizations, or the target architecture of this line is not supported by the current debugger code type.
    具有本机调试的
  1. C#,具有混合调试的C++和C++/CLI:请参阅第一点,行为是相同的。
  2. 不带本机调试的 C#、使用本机调试的 C++ 和具有混合调试的 C++/CLI:与第 2 点相同。

我拥有的代码如下:

C++ Native.hpp:

#pragma once
namespace native
{
class Native
{
public:
Native();
bool here() const;
};
}

C++ 原生.cpp:

#include "Native.hpp"
#include <iostream>
namespace native
{
Native::Native()
{
std::cout << "Created native entity!" << std::endl; // breakpoint here
}
bool Native::here() const
{
std::cout << "Native is here!" << std::endl; // breakpoint here
return true;
}
}

C++/CLI Wrapper.h:

#pragma once
#include "../cpp/Native.hpp"
using namespace System;
namespace clr
{
public ref class Wrapper
{
public:
Wrapper() 
{ 
Console::WriteLine("Building wrapper for native"); // breakpoint here
mNative = new native::Native(); 
}
~Wrapper() { delete mNative; }
bool go() 
{ 
Console::WriteLine("In wrapper to find native..."); // breakpoint here
return mNative->here(); 
}
private:
native::Native* mNative;
};
}

和 C#:

using System;
using clr;
namespace csharp
{
class Program
{
static void Main(string[] args)
{
Wrapper w = new Wrapper();
Console.WriteLine("Finding native through wrapper...");
w.go();
Console.WriteLine("Waiting...");
Console.Read();
}
}
}

我已经尝试了几乎所有我能想到的东西,但我无法调试C++端。我真的很感激任何帮助解决这个问题。

它可以像Enable native code debugging在Visual Studio中未启用一样简单。

learn.microsoft.com的教程:在同一调试会话中调试 C# 和C++包含成功调试 C#+C++ 会话的步骤。