可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm having trouble passing an argument from C++/CLI code into a .NET C# function.
In C++ I have something resembling the following:
void SomeFunction(short *id) { CSharpClass::StaticClassInstance->SetValue(id); }
On the C# side, the function is declared with a ref argument as:
public void SetValue(ref short id) { id = this.internalIdField; }
The compiler error I'm getting when calling SetValue(id) is "cannot convert parameter 1 from 'short *' to 'short %'".
I found out that a tracking reference (%) is equivalent to C# ref but I don't know how to use it with the short* parameter I'm trying to pass.
Thanks in advance.
回答1:
The logical C++/CLI signature of CSharpClass::SetValue
is
void SetValue(short% id);
If you know C++ (as opposed to C++/CLI), the answer here is the exact same as it would be if you had the C++ signature
void SetValue(short& id);
I.e., simply dereference the pointer:
void SomeFunction(short *id) { CSharpClass::StaticClassInstance->SetValue(*id); }
回答2:
If you want to be long winded, declare a tracking reference, assign the tracking reference to your id parameter and then pass the tracking reference to your function...
short %s = *id; SetValue (s);
If you'd rather not be long winded, just dereference the pointer. While the compiler cannot convert a short * into a short % it can convert a short into a short %...
SetValue (*id);