gpt4 book ai didi

c# - 如何在 C# 和 C++ 代码之间共享常量?

转载 作者:可可西里 更新时间:2023-11-01 16:30:39 25 4
gpt4 key购买 nike

我正在编写两个进程,其中一个使用 C# 和 WCF,第二个使用 C++ 和 WWSAPI。我希望能够在一个地方定义用于两者之间通信的地址,并让 C# 和 C++ 使用它。这可能吗?

我最接近的做法是在 IDL 中定义常量,然后使用 MIDL 和 TLBIMP 将其放入 C# 可以使用的 DLL 中。然而,这似乎并没有暴露常量,或者至少我无法弄清楚如何让它这样做。也许它仅限于类型定义。

还有什么建议吗?

最佳答案

您可以创建一个单独的 C++/CLI 项目并在 .h 文件中定义所有常量。例如,创建名为“ConstantBridge”的 C++/CLI 类库项目和名为“CSharpProgram”的 C# 项目:

常量.h

namespace Constants
{
const int MAGIC_NUMBER = 42;
}

// String literals must be defined as macros
#define MAGIC_PHRASE "Hello World"

// Since stirngs must be macros it's arguably more consistent
// to use `define` throughout. This is for demonstration purpose.

ConstantBridge.h

#include "Constants.h"

namespace ConstantBridge { public ref class ConstantBridge {
public:
// The use of the `literal` keyword is important
// `static const` will not work
literal int kMagicNumber = Constants::MAGIC_NUMBER;
literal String ^ kMagicPhrase = MAGIC_PHRASE;
};}

CSharpProgram.cs

Console.WriteLine(ConstantBridge.kMagicNumber); // "42"
Console.WriteLine(ConstantBridge.kMagicPhrase); // "Hello World"

现在,让“CSharpProgram”项目引用“ConstantBridge”项目。您的其他原生 C++ 项目可以简单地 #include "Constants.h"

只要您从ConstantBridge 项目中引用 literal,就不会生成运行时依赖项。您可以使用 ILSpy 进行验证或 ILdasm。 C# 中的 const 和 C++/CLI 中的 literal 在编译期间“按字面”复制到调用站点

关于c# - 如何在 C# 和 C++ 代码之间共享常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3146017/

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