托管 c++ 中的类从 c# 调用
时,我在托管 c++ dll 中贴上了一个类
public class IPHelper
{
public:
static void CheckIP(LPWSTR pSocketName);
static void DebugMessage(const wchar_t *str, ...);
private:
static DWORD GetIPInformation(PSOCKET_RECORD &pInfo);
};
当我成功编译它并将其添加为我的 c# 项目的引用 。 我可以使用名称空间,但是该类似乎是空的,并且我无法调用其中的函数。
有什么想法吗?
I have a class decalred inside managed c++ dll as
public class IPHelper
{
public:
static void CheckIP(LPWSTR pSocketName);
static void DebugMessage(const wchar_t *str, ...);
private:
static DWORD GetIPInformation(PSOCKET_RECORD &pInfo);
};
I compiled it successfully and add it as reference to my c# project.
I am able to use the namespace, however the class seems empty and I'm unable to call the functions inside it.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该类不是托管的,它是本机的。如果您想从托管代码中使用它,则需要将其称为
公共引用类
。That class is not managed, it is native. You need to call it a
public ref class
if you want to use it from managed code.您将需要使用 P/Invoke 方法来调用它。有关详细信息,请参阅此参考。
You're going to need to invoke it using the P/Invoke method. See this reference for more information.
正如其他人所指出的,这是一个本机 C++ 类。假设您的项目启用了 CLR,那么您可以轻松地围绕它编写一个简单的 C++/CLI 包装器,这将允许您在托管上下文中使用它。
这是 C++ / CLI 的快速概述,应该可以帮助您正确入门方向。
As others have noted, that's a native C++ class. Assuming your project is CLR enabled, then you can easily write a simple C++ / CLI wrapper around it, which will allow you to use it in a managed context.
This is a quick overview of C++ / CLI which should get you started in the right direction.
那个班级似乎是一个混合体。您指定了公共类 IPHeper,这就是您想要的一半。您应该将其指定为公共引用类 IPHelper。然而即便如此,由于它接收的参数类型,它仍然无法与托管类很好地交互。例如,wchar_t 与 System::String^(声明字符串的托管 C++ 方式)不同。同样,LPWSTR 也与 System::String^ 不同。附带说明一下,您最好编写一些实用程序方法来在 .NET System::Strings 和 wchar_t 以及您最可能需要的其他本机字符串之间进行转换。 这是 MSDN 上一篇关于如何在所有不同类型之间进行转换的优秀文章字符串类型。
现在我不知道您是否想将此类直接公开给 C#,或者让此类由比此处更好的托管包装器来包装。但无论如何,托管 C++ 类的方法必须采用 .NET 类型才能直接在 C# 代码中使用。
That class seems to be a hybrid. You specified public class IPHelper, which is halfway what you want. You should specify it as public ref class IPHelper. However even so, it will still not interface well with managed classes, because of the parameter types it receives. For instance a wchar_t is not the same as a System::String^ (managed C++ way to declare strings). Similarly a LPWSTR is also not the same as a System::String^. As a side note, it would be best for you to write some utility methods to convert between .NET System::Strings and wchar_t and other native strings that you will most likely need. This is an excellent article on MSDN on how to convert between all the various string types.
Now I don't know if you want to expose this class directly to C#, or have this class in turn wrapped by a better managed wrapper than what you have here. But anyway you do it, the Managed C++ class's methods have to take .NET types in order to be directly used in C# code.