如何将C++函数转换为C#函数

3

我正在研究Amibroker C#插件项目。Amibroker SDK是用C++编写的,但我正在使用一个C#插件,它完全可以像Amibroker C++一样执行C#插件链接

C#插件中的所有内容都正常工作,除了一个用C++编写的函数:

PLUGINAPI struct RecentInfo* GetRecentInfo(LPCTSTR ticker)
{
   //Process & return RecentInfo* (RecentInfo is a structure)
}

在C#标准插件中,它被转换为以下方式。
public RecentInfo GetRecentInfo(string ticker)
{
    //Process & Return RecentInfo
}

很不幸,Amibroker应用程序在这种错误转换下崩溃。因此,我试图按照自己的方式进行转换,以使Amibroker应用程序正常运行,但多次尝试失败。
以下是我迄今为止尝试过的方法:

尝试1:

unsafe public RecentInfo* GetRecentInfo(string ticker)
{
    //Process & Return RecentInfo* (RecentInfo structure is declared as unsafe)
}

影响:

Amibroker 应用程序无法加载。

尝试 2:

public IntPtr GetRecentInfo(string ticker)
{
    //Process & Return Pointer using Marshal.StructureToPtr
}

影响:

Amibroker 应用程序无法加载

尝试3:

public void GetRecentInfo(string ticker)
{
    //Useless becoz no return type
}

影响:

Amibroker可以正确加载和调用函数,但如何返回结构指针呢?

因此,我正在思考将C++函数精确转换为C#的方法。


你尝试使用 ref RecentInfo 了吗? - user1814023
public ref RecentInfo GetRecentInfo(string ticker) //C# 不允许 - Ulhas Tuscano
我的意思是 - 如果您被允许更改GetRecentInfo的签名,那么请从调用方法中为RecentInfo结构分配内存,然后将其作为引用参数传递给GetRecentInfo方法。 - user1814023
1个回答

2
如果完全使用C#编写,那么这很好,认为问题在于实现而不是调用。
public RecentInfo GetRecentInfo(string ticker)
{
      RecentInfo rc;
    //Process & Return RecentInfo
      return rc;
}

或者这样,(您也可以使用ref)
public void GetRecentInfo(string ticker,out RecentInfo rc )
{
rc=new RecentInfo();
....process

 return ;
}

我不了解Amibroker。但是什么是崩溃报告或异常?它说了什么?它完全是用C#编写的还是仍然调用了C++? - qwr
崩溃报告显示“EXCEPTION_ACCESS_VIOLATION”。 - Ulhas Tuscano
1
在 MSDN 上:当代码尝试读取或写入未分配的内存,或者没有访问权限的内存时,在非托管或不安全代码中会发生访问冲突。因此,要检查函数内部是否调用了某些非托管函数或不安全的 C# 代码。 - qwr
请检查空引用。可能您忘记初始化了。 - qwr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接