简体   繁体   English

将Borland C ++方法公开到C#

[英]Expose Borland C++ methods to C#

I have following method in my Borland C++ code, 我在Borland C ++代码中有以下方法,

static bool UploadBitstream(void)
{
   //Some code Implementation
}

And I'm trying to convert it to DLL and access it in C#. 我正在尝试将其转换为DLL并在C#中访问它。

What are the steps I need to follow to Convert the code DLL and then use it in C# ?? 我需要执行以下步骤来转换代码DLL,然后在C#中使用它?

First, you have to make sure that the methods are defined extern. 首先,必须确保方法是外部定义的。 Then you need to declare the method stdcall or pascal calling convention, and mark them dllexport. 然后,您需要声明方法stdcall或pascal调用约定,并将它们标记为dllexport。 See code listing below (this is ancient memory for me, so pardon if I am a bit off on modern Borland C++ compilers). 请参见下面的代码清单(对我来说这是古老的记忆,如果我对现代的Borland C ++编译器不满意,请原谅)。

// code.h
extern "C" {

#define FUNCTION __declspec(dllexport)

FUNCTION int __stdcall   SomeFunction(int Value);    

In the main 在主要

#include "code.h"

FUNCTION int __stdcall SomeFunction(int timesThree)
{
    return timesThree * 3;
}

Once you've compiled your DLL all you should need to do in .NET to get access to it is use the DLLImport property. 编译完DLL之后,只需使用DLLImport属性即可在.NET中进行访问以访问它。

public class stuff
{
    [DLLImport("somedll.dll")]
    public static extern void UploadBitstream();
}

If you need pointers or anything like that it gets more complicated but for void functions it's that simple. 如果您需要指针或类似的东西,它会变得更加复杂,但是对于void函数而言,就是这么简单。

It should be noted that once you invoke that function the dll will be loaded by your program and won't be released until your program is closed. 应该注意的是,一旦您调用该函数,该dll将被您的程序加载,直到您的程序关闭,该dll才会被释放。 You can dynamically load dlls but that is much more complicated. 您可以动态加载dll,但这要复杂得多。 I can explain it here if you have a need. 如果您有需要,我可以在这里解释。

Watch your terminology. 注意您的术语。
In your example UploadBitstream is function not a method. 在您的示例中,UploadBitstream是函数而非方法。
If it is indeed a method in a class then it is very difficult to use classes from Borland compiled DLLs. 如果确实是类中的方法,则很难使用Borland编译的DLL中的类。

If your code is actually C not C++ you should be able to create a compatible DLL for your simple C style functions with C++ Builder. 如果您的代码实际上是C而不是C ++,则应该可以使用C ++ Builder为简单的C样式函数创建兼容的DLL。

See the following SO question: Use a dll from a c++ program. 请参阅以下SO问题: 使用c ++程序中的dll。 (borland c++ builder and in general) where I list various compiler settings which will also apply to creating compatible DLLs. (Borland C ++ Builder和一般而言) ,其中列出了各种编译器设置,这些设置也将适用于创建兼容的DLL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM