开发者

C# extern int? How do I make a global var across classes and namespaces?

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 ( "SilverlightAppl开发者_如何学Cication37.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


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; }
}


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.


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();


public static int EventCount; should do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜