• 0

C++ to C# (converting libraries)


Question

Heya, 
This is my first post and I hope I don't break any rules (which I did read :)). Anyway, here is my problem:
 
I have a project which I would really like to do in C# to expand my knowledge with this specific programming language. However, the libraries for this project are written in C++.
 
I won't ask for someone to convert the whole thing, because that's just very unfair (and breaks the rules I think :p). So I will just ask for the following the be explained in plain English! 
 
(In C++)
What does:
#ifndef
#include
#define
#void
...all mean or represent?
 
Thanks very much!
Swampy
 
Here is the code in full (in C++) just incase anyone would like to read it:

http://pastebin.com/nUQ7npTR

 

(This was initially made by Adafruit, the help support team said that they were ok with converting their code as long as it was not for commercial use (which it's not, it's a home project! :D).

 

Thanks again!

 

Link to comment
https://www.neowin.net/forum/topic/1259864-c-to-c-converting-libraries/
Share on other sites

23 answers to this question

Recommended Posts

  • 0

The keywords starting with # are called "compiler directives". #ifndef means "if not defined" #define is used to define a constant. #include includes a (header) file. Those aren't exactly part of the C++ language spec and you don't see them very often unless you're working with device driver libraries and such (which this looks like).

 

I don't see a #void in this code but void as in C++ void type. In OOP languages like C++ and C# methods or functions have a return type (int, string, etc) or void if the function or method doesn't return any value. 

 

// Returns a value (of type Int)

public int Add(int a, int b)

{

  return a + b;

}

 

// Doesn't return a value (ie. void)

public void Sleep()

{

  Thread.Sleep(1000);

}

 

I'm probably not the best person to explain all this though...

  • 0
  On 11/06/2015 at 18:23, Obry said:

The keywords starting with # are called "compiler directives" and not really part of the C++ language specification. #ifndef means "if not defined" #define instructs the compiler to define a constant. Those aren't exactly part of the C++ language spec and you don't see them very often unless you're working with device driver libraries and such (which this looks like).

 

#ifndef -> "if not defined"

#define -> defines a project constant

#include -> include a (header) file

 

I don't see a #void in this code but void as in C++ void type. In OOP languages like C++ and C# methods or functions have a return type (int, string, etc) or void if the function or method doesn't return any value. 

 

Ex:

 

public int add(int a, int b)

{

  return a + b;

}

 

public void doNothing()

{

 

}

Oh alrighy thanks!

So is there a function or some kind of operator for, if not defined for C#?

  • 0

Yes it does - #define, #ifndef, #if #endif, etc. It does not have #include directive though. You won't see much of that in C# (is what I should've said in my first post).

 

In C# you generally include your external libraries as part of your project and then use:

 

using Vendor.Library.SomeNamespace;

using Vendor.Library.SomeNamespace.SubNamespace;

 

(instead of #include)

 

That being said, you should be able to include C++ libraries (compiled into .dll) in C# and use them that way without having to re-write them.

 

Check this out ( searching on google will give you a lot more 

  • 0
  On 11/06/2015 at 18:39, Obry said:

Yes it does - #define, #ifndef, #if #endif, etc. It does not have #include directive though. You won't see much of that in C# (is what I should've said in my first post).

 

In C# you generally include your external libraries as part of your project and then use:

 

using Vendor.Library.SomeNamespace;

using Vendor.Library.SomeNamespace.SubNamespace;

 

(instead of #include)

 

That being said, you should be able to include C++ libraries (compiled into .dll) in C# and use them that way without having to re-write them.

 

Check this out ( searching on google will give you a lot more 

If you would like to see the whole provided files: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

 

To my knowledge I would be doing

using .... (and so on) when it comes to this. I thought using was combine file properties. (I don't think that makes much sense). This libary was giving properties to the addresses for this device.

  • 0

void is the return type of the function, in this case 

void write8(uint8_t addr, uint8_t d);

is a function called write8 that returns void, that is it returns nothing.

 

The #include, #define, etc. are compiler pre-processor directives. They are instructions to the compiler to do before it does anything else.

 

#include will include whatever file is specified. #if is a conditional. So the following code 

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

mean if ARDUINO is defined to be of greater-than-or-equal to 100 it will include the file Arduino.h otherwise it will include WProgram.h

 

The .h files are header files, in this case they are not standard library header files but ones provided as part of that adafruit library. You will come across two types of #include directives generally. Ones with the filename enclosed in double quotes are custom header files and their location is relative to the source file. Ones enclosed between angle brackets are standard library headers such as iostream.

 

#define is an old C way of defining a constant. So the following code 

#define PCA9685_SUBADR1 0x2

Will declare a constant called PCA9685_SUBADR1 with the value of 0x2

 

What the compiler does in this case is everywhere it sees PCA9685_SUBADR1 in your source file it will do a simple search and replace of the value 0x2. 

 

And lastly the following code

#ifndef _ADAFRUIT_PWMServoDriver_H

means If Not Defined so if _ADAFRUIT_PWMServoDriver_H is not already defined then the following #define will define it. If it is already defined then the #define on the following line is skipped over so as to not try and define it again.

 

Hope that helps?

  • 0
  On 11/06/2015 at 19:45, kozukumi said:

void is the return type of the function, in this case 

void write8(uint8_t addr, uint8_t d);

is a function called write8 that returns void, that is it returns nothing.

 

The #include, #define, etc. are compiler pre-processor directives. They are instructions to the compiler to do before it does anything else.

 

#include will include whatever file is specified. #if is a conditional. So the following code 

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

mean if ARDUINO is defined to be of greater-than-or-equal to 100 it will include the file Arduino.h otherwise it will include WProgram.h

 

The .h files are header files, in this case they are not standard library header files but ones provided as part of that adafruit library. You will come across two types of #include directives generally. Ones with the filename enclosed in double quotes are custom header files and their location is relative to the source file. Ones enclosed between angle brackets are standard library headers such as iostream.

 

#define is an old C way of defining a constant. So the following code 

#define PCA9685_SUBADR1 0x2

Will declare a constant called PCA9685_SUBADR1 with the value of 0x2

 

What the compiler does in this case is everywhere it sees PCA9685_SUBADR1 in your source file it will do a simple search and replace of the value 0x2. 

 

And lastly the following code

#ifndef _ADAFRUIT_PWMServoDriver_H

means If Not Defined so if _ADAFRUIT_PWMServoDriver_H is not already defined then the following #define will define it. If it is already defined then the #define on the following line is skipped over so as to not try and define it again.

 

Hope that helps?

 

Very much so!

I don't suppose you could show me how it would look in C#?

(I'm referring to: #if ARDUINO >= 100

#include "Arduino.h"

#else

#include "WProgram.h"

#endif)

 

and so would the #define PCA9685_SUBADR1 0x2 be written as        const string PCA9685_SUBADR1 = "0x2";?

  • 0
  On 11/06/2015 at 20:21, SwampyPk said:

Very much so!

I don't suppose you could show me how it would look in C#?

(I'm referring to: #if ARDUINO >= 100

#include "Arduino.h"

#else

#include "WProgram.h"

#endif)

 

and so would the #define PCA9685_SUBADR1 0x2 be written as        const string PCA9685_SUBADR1 = "0x2";?

 

Sorry but I don't know enough C# to know how you would or if it is even possible to use the C++ headers in your C# app. 

  • 0

#if and #define don't work quite the same way in C# as they do in C++.

#define in C++ can be used by itself with just an identifier, (#define DEBUG) or it can be assigned a value, (#define constValue 1) or it can be used as a macro that is replaced with code at compile time (#define INC_VALUE(val) val++).

C#'s define directive only can be used as in the first case. It's essentially a Boolean flag where it exists or it doesn't.

C# also doesn't have "ifndef" or "ifdef". You just use #if and the NOT operator. (#if DEBUG or #if !DEBUG).

Includes in C# are made using the "using" keyword rather than the include preprocessor command, so you would use "using Arduino;" at the top of your source file. This would require you have something that is in that namespace, of course.

You can call c++ library functions from C#, it's just a bit more complicated. The library either needs to be COM+ or you have to create platform invoke functions for the library.

  • 0

All of the answers so far are micro focused on a literal reply to the question and ignores the context where the person asking the question by the very nature of the question might actually be asking the wrong question - yeah parse that.

 

Google tells me that Swampy is probably looking for something like this:

 

https://github.com/raspberry-sharp/raspberry-sharp-io

 

He wants to use C# to talk to some hardware via industry standard I2C protocol.

 

Pca9685 is sample code for his device:

 

https://github.com/raspberry-sharp/raspberry-sharp-io/tree/master/Raspberry.IO.Components/Controllers/Pca9685

  • 0
  On 11/06/2015 at 20:50, Eric said:

You can call c++ library functions from C#, it's just a bit more complicated. The library either needs to be COM+ or you have to create platform invoke functions for the library.

 

That option would asume he is running the C# code on Windows. If so, he has some larger issues to deal with such as writing a device driver or using the parallel port that may not exist etc.

  • 0

I have noticed, and has been pointed out that I did lack some context. Well here it is :D.

 

I currently have a Raspberry Pi 2 in my possession, this RasPi is currently connected to a 'Adafruit 16-channel Servo hat'. Amongst many of it's features, for this problem, my only concern is for the 3 servos I have connected to servo-Output ports (if you care what ports: 1,3 and 5).

 

As I have said before, I wanted to expand my knowledge in C# and decided to try and program it in that language, however, I noticed their libraries were written in C++ (also python, but I'm not too bothered about that). 

 

I had two possible solutions (which I think were my only two):

1). Try and rewrite them into C#

2). Try and see if there was any possibility to use the C++ libraries in my C# program to use the servos.

 

Thanks very much everyone!

Swampy

 

PS: I am using the I2C protocol to communicate between the RasPi and the servo hat. 

  • 0
  On 11/06/2015 at 21:02, DevTech said:

All of the answers so far are micro focused on a literal reply to the question and ignores the context where the person asking the question by the very nature of the question might actually be asking the wrong question - yeah parse that.

 

Google tells me that Swampy is probably looking for something like this:

 

https://github.com/raspberry-sharp/raspberry-sharp-io

 

He wants to use C# to talk to some hardware via industry standard I2C protocol.

 

Pca9685 is sample code for his device:

 

https://github.com/raspberry-sharp/raspberry-sharp-io/tree/master/Raspberry.IO.Components/Controllers/Pca9685

 

 

I think the second link is the C++ to C# converted version. Am I wrong?

 

C++ version:

http://pastebin.com/nUQ7npTR

 

C# version:

https://github.com/raspberry-sharp/raspberry-sharp-io/blob/master/Raspberry.IO.Components/Controllers/Pca9685/Pca9685Connection.cs

  • 0
  On 11/06/2015 at 22:18, SwampyPk said:

I have noticed, and has been pointed out that I did lack some context. Well here it is :D.

 

I currently have a Raspberry Pi 2 in my possession, this RasPi is currently connected to a 'Adafruit 16-channel Servo hat'. Amongst many of it's features, for this problem, my only concern is for the 3 servos I have connected to servo-Output ports (if you care what ports: 1,3 and 5).

 

As I have said before, I wanted to expand my knowledge in C# and decided to try and program it in that language, however, I noticed their libraries were written in C++ (also python, but I'm not too bothered about that). 

 

I had two possible solutions (which I think were my only two):

1). Try and rewrite them into C#

2). Try and see if there was any possibility to use the C++ libraries in my C# program to use the servos.

 

Thanks very much everyone!

Swampy

 

PS: I am using the I2C protocol to communicate between the RasPi and the servo hat. 

 

 

Well you gave 1/2 the context. You are using Raspberry Pi 2 hardware.

 

Next, which O/S - there are quite a few which run on that board.

 

Since you want to use C#, Windows 10 is a natural fit:

 

http://www.hanselman.com/blog/SettingUpWindows10ForIoTOnYourRaspberryPi2.aspx

 

Or the default Linux where C# is implemented in the Mono project.

  • 0
  On 11/06/2015 at 22:25, SwampyPk said:

I think the second link is the C++ to C# converted version. Am I wrong?

 

C++ version:

http://pastebin.com/nUQ7npTR

 

C# version:

https://github.com/raspberry-sharp/raspberry-sharp-io/blob/master/Raspberry.IO.Components/Controllers/Pca9685/Pca9685Connection.cs

 

A very quick look at both suggests to me that the Raspberry Sharp project is not a "conversion" (http://www.raspberry-sharp.org/)

 

Note that in your fruit code, the main I2C comm is in some library named "Wire" which is not in that project

 

There is so little code in that adafruit sample that "conversion" is not really a useful pattern. Just understand what is doing and implement it in C# or perhaps just ignore the adafruit code and start with the Raspberry Sharp project which has a bunch of useful C# code that at a quick glance appears to be just fine as an example of C# programming.

 

Also, that Githib code is the first thing I found on a quick search so I could plop in an example, so there may be lots of other stuff on GitHub - search with "Raspberry" maybe and other source code places on the internet

  • 0
  On 11/06/2015 at 22:51, DevTech said:

Well you gave 1/2 the context. You are using Raspberry Pi 2 hardware.

 

Next, which O/S - there are quite a few which run on that board.

 

Since you want to use C#, Windows 10 is a natural fit:

 

http://www.hanselman.com/blog/SettingUpWindows10ForIoTOnYourRaspberryPi2.aspx

 

Or the default Linux where C# is implemented in the Mono project.

I am using the Raspian O/S. However, I will probably change it to windows 10.

 

Will do that tomorrow :D

  On 11/06/2015 at 23:00, DevTech said:

A very quick look at both suggests to me that the Raspberry Sharp project is not a "conversion" (http://www.raspberry-sharp.org/)

 

Note that in your fruit code, the main I2C comm is in some library named "Wire" which is not in that project

 

There is so little code in that adafruit sample that "conversion" is not really a useful pattern. Just understand what is doing and implement it in C# or perhaps just ignore the adafruit code and start with the Raspberry Sharp project which has a bunch of useful C# code that at a quick glance appears to be just fine as an example of C# programming.

 

Also, that Githib code is the first thing I found on a quick search so I could plop in an example, so there may be lots of other stuff on GitHub - search with "Raspberry" maybe and other source code places on the internet

 

The thing is, I spoke to the Adafruit help developers and we couldn't find a good version in C#. :/

 

I will keep researching :).

  • 0
  On 11/06/2015 at 23:56, SwampyPk said:

 

The thing is, I spoke to the Adafruit help developers and we couldn't find a good version in C#. :/

 

 

 

Again, there just is not a lot of code there. The Raspberry Sharp project has two GitHub projects, one general libe and an I/O lib

 

So you could grab bits n pieces of each to implement I2C and then use the device specific bits from Raspberry Sharp and Adafruit to add your servo board specifics. Don't try for a direct conversion since the Adafruit code is crap from a C# point of view.

 

Start with the smallest thing that could possibly work such as a repeating  I2C bitstream to a pin. I would have to imagine that various people have cobbled up I2C monitor software for a PC that you can use like an oscilliscope to see if your code makes proper I2C. Your turn to google and let me know if my guess is correct...

  • 0
  On 12/06/2015 at 00:37, DevTech said:

Again, there just is not a lot of code there. The Raspberry Sharp project has two GitHub projects, one general libe and an I/O lib

 

So you could grab bits n pieces of each to implement I2C and then use the device specific bits from Raspberry Sharp and Adafruit to add your servo board specifics. Don't try for a direct conversion since the Adafruit code is crap from a C# point of view.

 

Start with the smallest thing that could possibly work such as a repeating  I2C bitstream to a pin. I would have to imagine that various people have cobbled up I2C monitor software for a PC that you can use like an oscilliscope to see if your code makes proper I2C. Your turn to google and let me know if my guess is correct...

 

Good plan :D I'll report back soon.

  • 0

Is there an Arduino C# library that you are already using or wanted to use?

Converting the library (I found the source on Github) is very simple, but it's interfacing with Arduino's Wire library so that would also need to either be implemented if there isn't an existing project for it.

This topic is now closed to further replies.
  • Posts

    • Just checked for updates on my Windows 11  machines and my Windows 10 machines. Windows 10 is getting the June cumulative but my Windows 11 machines aren't finding a June cumulative.  Odd.
    • Microsoft to default-block more files in New Outlook and Outlook Web by Sayan Sen Back in 2019, Microsoft announced a big change to its list of blocked file types for attachments. At the time, Microsoft stated that it was doing so to improve security by adding "file extensions to the BlockedFileTypes property of existing OwaMailboxPolicy objects." The tech giant deems such file types as no longer secure for attachments and is a good way to protect customers from potentially malicious attacks from threat actors. Over time the company has expanded the block list for Outlook for the Web and also the New Outlook for Windows app. In a new message via the Microsoft 365 Admin Center portal, the company has announced that two more such file types will be added. However, the tech giant feels this should not affect most users, as these "newly blocked file types are rarely used." It writes: "As part of our ongoing efforts to enhance security in Outlook Web and the New Outlook for Windows, we’re updating the default list of blocked file types in OwaMailboxPolicy. Starting in early July 2025, the following file types will be added to the BlockedFileTypes list: .library-ms .search-ms" For admins, Microsoft says that no action is required if their respective organisations do not rely on the aforementioned file attachments. However, if they are still in use, then admins can "add them to the AllowedFileTypes property of your users’ OwaMailboxPolicy objects before the rollout." Speaking of which, this is set as a "major change" with the rollout expected to start in early July 2025. You can find information on how to do that in the official documentation on Microsoft's website here. For those wondering, the following file types are allowed by default: ".avi, .bmp, .doc, .docm, .docx, .gif, .jpg, .mp3, .one, .pdf, .png, .ppsm, .ppsx, .ppt, .pptm, .pptx, .pub, .rpmsg, .rtf, .tif, .tiff, .txt, .vsd, .wav, .wma, .wmv, .xls, .xlsb, .xlsm, .xlsx, .zip" You can find the list of blocked file types here on this Microsoft support article on the company's official website. If you are a system admin, you can view the message on the Microsoft 365 Admin Center under ID MC1090702.
    • Thanks Nik. This card is kinda what I'm looking for. Do you know if this connects to the motherboard via the TB Header / JTBT1 Header or if this is via the PCI Express slot? I was wondering if there was just a cable I could purchase that would give me a TB connection, since the header is already on the mainboard. Thanks
    • Adobe Acrobat Reader DC 2025.001.20531 by Razvan Serea Adobe Acrobat Reader DC software is the free, trusted standard for viewing, printing, signing, and annotating PDFs. Its the only PDF viewer that can open and interact with all types of PDF content – including forms and multimedia. It’s connected to Adobe Document Cloud – so you can work with PDFs on computers and mobile devices. Adobe Document Cloud is a revolutionary, modern and efficient way to get work done with documents in the office, at home or on-the-go. At the heart of Document Cloud is the all-new Adobe Acrobat DC, which will take e-signatures mainstream by delivering free e-signing with every individual subscription. Document Cloud includes a set of integrated services that use a consistent online profile and personal document hub. With Adobe Document Cloud, people will be able to create, review, approve, sign and track documents whether on a desktop or mobile device. Businesses will be able to take advantage of Document Cloud for enterprise which provides enterprise-class document services that integrate into systems of record such as CRM, HCM, CLM, and CMS, adding speed, efficiency and transparency to getting business done with documents. Adobe Acrobat Reader DC new feature highlights: Work with PDFs from anywhere with the new, free Acrobat DC mobile app for Android or iOS. Select functionality is also available on Windows Phone. Use the new Fill & Sign tool in your desktop software to complete PDF forms fast with smart autofill. Download the free Adobe Fill & Sign mobile app to add the same option to your iPad or Android tablet device. Save money on ink and toner when printing from your Windows PC. Store and access files in Adobe Document Cloud with 5GB of free storage. Get instant access to recent files across desktop, web, and mobile devices with Mobile Link. Sync your Fill & Sign autofill collection across desktop, web, and iPad devices. Adobe PDF Pack premium features includes: Convert documents and images to PDF files. Use your mobile device camera to take a picture of a paper document or form and convert it to PDF. Turn PDFs into editable Microsoft Word, Excel, PowerPoint, or RTF files. Combine multiple files into a single PDF (web only). Get signatures from others with a complete e-signature service. Send, track, and confirm delivery of documents electronically instead of using fax or overnight services (tracking not available on mobile). Store and access files online with 20GB of storage. Download: Adobe Acrobat Reader DC 64-bit | 626.0 MB (Freeware) Download: Adobe Acrobat Reader DC 32-bit | 516.0 MB Link: Adobe Acrobat Reader DC Home Page | Release Notes | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Reacting Well
      Alan- earned a badge
      Reacting Well
    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      494
    2. 2
      ATLien_0
      268
    3. 3
      +FloatingFatMan
      223
    4. 4
      +Edouard
      200
    5. 5
      snowy owl
      141
  • Tell a friend

    Love Neowin? Tell a friend!