C# 外部整数?如何跨类和命名空间创建全局变量?

发布于 2024-10-10 13:37:58 字数 546 浏览 0 评论 0原文

作为一名老 C/C++ 程序员,我想在整个过程中保留一个全局 int 计数器 我的所有命名空间和类。

public static extern int EventCount;

不工作; VS2010 编译器不允许我使用 extern int。 即使使用DLLImport

[DllImport ( "SilverlightApplication37.dll" )]
public static extern int EventCount;

VS2010 抱怨,

Error   1   The modifier 'extern' is not valid for this item    

那么我如何在所有代码中拥有全局 int 呢?

干杯!

K博士

As an old C/C++ programmer, I want to keep a global int counter across
all of MY namespaces and classes.

public static extern int EventCount;

Is not working; the VS2010 compiler won't let me have an extern int.
Even with a DLLImport.

[DllImport ( "SilverlightApplication37.dll" )]
public static extern int EventCount;

VS2010 complains,

Error   1   The modifier 'extern' is not valid for this item    

So how do I have a global int across all my code?

Cheers!

dr.K

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七色彩虹 2024-10-17 13:37:58

没有这样的事情。为了保存数据,C# 有字段、属性和局部变量。您可以创建一个静态类,然后创建一个属性,如下所示:

public static class GlobalData
{    
    public static int EventCount { get; set; }
}

There is no such thing. For holding data, C# has fields, properties and local variables. You can make a static class and then create a property, like this:

public static class GlobalData
{    
    public static int EventCount { get; set; }
}
酒几许 2024-10-17 13:37:58

我倾向于做的是创建一个新的静态类,其中包含静态字段来存储全局变量。它总是被称为“GlobalValues”或类似名称。

What I tend to do is to create a new static class with static fields to store global variables. It's always called "GlobalValues" or similar.

七分※倦醒 2024-10-17 13:37:58

我还没有找到通过 C# 直接访问 C dll 中的全局变量的解决方案。但是,如果您有权访问 dll 源代码,则可以为全局添加访问器函数。

因此,如果在您的 C 库中您有:

__declspec(dllexport) extern int EventCount;

您将需要添加:

__declspec(dllexport) int __cdecl getEventCount(void);

int __decl getEventCount(void) {
    return EventCount;
}

然后在您的 C# 代码中的某处您将需要类似的内容:

[DllImport("SilverlightApplication37.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Int32 getEventCount();

I haven't been able to find a solution to directly access a global variable in a C dll via C#. But, if you have access to the dll source code you can add an accessor function for the global.

So if in your C library you have:

__declspec(dllexport) extern int EventCount;

You will need to add:

__declspec(dllexport) int __cdecl getEventCount(void);

int __decl getEventCount(void) {
    return EventCount;
}

Then in your C# code somewhere you will need something like:

[DllImport("SilverlightApplication37.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Int32 getEventCount();
╰沐子 2024-10-17 13:37:58

public static int EventCount; 应该可以解决问题。

public static int EventCount; should do the trick.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文