在人们拆开这个问题之前,我会解释一下我想做什么。
我目前有一个可以访问共享内存的 C 程序。 C 程序通过#defined 偏移量导航此共享内存。示例:
#define VAR_1 0x2000
现在我有一个 C# 程序可以显示共享内存中的数据。我正在尝试确定如何使用我的 C 程序使用的 #defines 并让我的 C# 程序也引用它们。
我试图避免维护包含这些定义的两个文件。
因此,C# 程序是否可以使用 .h 文件中的#defines?
谢谢,
最佳答案
The
#define
directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.
你可以这样做:
常量.cs:
#if __STDC__
#define public
#else
namespace foo
{
class Constants {
#endif
public const int VAR_1 = 0x2000;
#if __STDC__
#undef public
#else
}
}
#endif
主.c:
#include <stdio.h>
#include "constants.cs"
int main(void)
{
printf("%d\n", VAR_1);
return 0;
}
程序.cs:
using System;
namespace foo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Constants.VAR_1);
}
}
}
这导致:
$ gcc -Wall -Wpedantic main.c && ./a.out
8192
$ dotnet run
8192
这是在 C 中使用 const int
而不是 #define
,但这可能是您愿意做出的权衡。
关于c# - C# 是否具有与#def 常量等效的#include?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198618/