4

我在 C 中有一个接受十六进制参数的函数。我需要从 C# 调用这个函数。我目前的方法似乎不正确,因为我的 C 函数返回了错误的数字。

这是我的 C 函数的声明:

enum tags {
    TAG_A = -1,
    TAG_B  = 0x00, 
    TAG_C = 0xC1,  
    ...
};
int myfunction(enum tags t);

这是我的 C# 代码:

enum tags {
    TAG_A = -1,
    TAG_B  = 0x00, 
    TAG_C = 0xC1, 
    ...
    }

[DllImport ("mylibraryname")]
    public static extern int myfunction(tags t);

myfunction(tags.TAG_B);

我在 Mac 上,我使用 Mono 和 Xcode 来完成所有这些工作。可以假定 C 函数是正确的,因为它是我下载的开源库。我认为十六进制数字有问题,但我不确定。

解决方案:

我勾选了一个答案,尽管实际上将 C# 枚举设置为长期解决了我的问题。所以在 C# 中,我有:

枚举标签:长 { TAG_A = -1,TAG_B = 0x00,TAG_C = 0xC1,...}

4

2 回答 2

2

Hexadecimal is simply a different way of expressing a literal integer value. It's irrelevant to your problem. For instance TAG_B = 0x00 and TAG_B = 0 both mean exactly the same thing.

The problem is possibly that the C enum is a 16 bit integer, whereas the C# enum is 32 bit. Instead of creating an enum in C#, try just doing it as straight Int32 values:

static class tags 
{
    public static short TAG_A = -1;
    public static short TAG_B  = 0x00;
    public static short TAG_C = 0xC1;
    // ...
}

[DllImport ("mylibraryname")]
public static extern int myfunction(short t);

myfunction(tags.TAG_B);

Or, as L.B suggested, you can just set the type of the enum members:

enum tags:short 
{
    TAG_A = -1,
    TAG_B  = 0x00, 
    TAG_C = 0xC1,
    // ...
}
于 2012-11-19T13:15:09.353 回答
0

On my architecture sizeof(enum_t), where enum_t is a typedef of an enum returns 4 bytes, so if the C# enum is 4 bytes as well i can't see the problem.

Check the size of the enum with sizeof for your architecture, if they match the problem is somewhere else.

于 2012-11-19T13:16:31.533 回答