[英]Passing in C# enum to a wrapper method parameter of C++ CLI
I have a following C++/CLI class. 我有以下C ++ / CLI类。
public ref class QADotNetAPI {
public:
QADotNetAPI() {
}
~QADotNetAPI() {
QTTerminate();
}
int SomeMethod(const char *ch) {
return Something(ch);
}
.
.
.
int IsValid(QTQualifier *pstate) {
return QTIsValid(QTFeatureIdEnum::_QT_FEATURE_ALL, pstate);
}
};
.
.
.
// The method in unmanaged code ( Not within QADotNetAPI scope )
QT_API QTErrorCode QTIsValid(const QTFeatureId eFeatureId, QTQualifier *eState );
.
.
.
// The enum, QTQualifier. ( Not within QADotNetAPI scope )
typedef enum QTQualifierEnum
{
QT_QUALIFIER_OUT_OF_RANGE,
QT_QUALIFIER_CORRECTABLE,
QT_QUALIFIER_VALID,
QT_QUALIFIER_LAST
} QTQualifier;
I injected this C++/CLI class above into C# application. 我将上面的C ++ / CLI类注入到C#应用程序中。 I can successfully invoke the
SomeMethod
. 我可以成功调用
SomeMethod
。 I can make it because I know what kind of value to pass into that function. 之所以能够做到这一点,是因为我知道传递给该函数什么样的价值。
But I don't know what to pass in for the QTIsValid method. 但是我不知道QTIsValid方法要传递什么。
public enum QaEnum {
OUTOFRANGE,
CORRECTABLE,
VALID,
LAST
}
private void button1_Click(object sender, EventArgs e)
{
QADotNetAPI qa = new QADotNetAPI();
int rst= qa.Init();
rst = qa.IsValid(ref QaEnum.VALID); // Doesn't work
// rst = qa.IsValid(out QaEnum.VALID); // Doesn't work too
// rst = qa.IsValid(?????) // WHAT TO PASS IN ??
}
Some say that "share the enum throughout C++/CLI and C# project". 有人说“在整个C ++ / CLI和C#项目中共享枚举”。 I tried that using a bunch of enum declarations and shared them via dll on both C++/CLI and C# projects but to no avail.
我尝试使用一堆枚举声明,并在C ++ / CLI和C#项目上通过dll共享它们,但无济于事。
Also, I tried with struct
. 另外,我尝试使用
struct
。 Again, it didn't work. 再次,它没有用。 What can I do for a C++/CLI consumable enum?
我可以为C ++ / CLI消耗枚举做什么?
The current signature of IsValid accepts only a pointer: IsValid的当前签名仅接受一个指针:
int IsValid(QTQualifier *pstate)
{
return QTIsValid(QTFeatureIdEnum::_QT_FEATURE_ALL, pstate);
}
So my expectation is that for C# that is shown as IntPtr. 因此,我的期望是将C#显示为IntPtr。 (Honestly I would expect that for the C# Compiler the method wouldn't be usable at all.) My suggestion ist to change IsValid as follows:
(老实说,我希望该方法对于C#编译器完全不可用。)我的建议是如下更改IsValid:
int IsValid(int state)
{
// TODO: check argument is valid
QTQualifier nativeState = static_cast<QTQualifier>(state);
return QTIsValid(QTFeatureIdEnum::_QT_FEATURE_ALL, &nativeState);
}
That should work. 那应该工作。
A more type safe version could be this 更安全的版本可能是这样
public enum class QaEnum
{
OUTOFRANGE,
CORRECTABLE,
VALID,
LAST
}
int IsValid(int state)
{
// TODO: check if argument is valid (.NET enums are also only integers)
QTQualifier nativeState = static_cast<QTQualifier>(state);
return QTIsValid(QTFeatureIdEnum::_QT_FEATURE_ALL, &nativeState);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.