• 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

    • Hello, The thing about Thunderbolt 2/3/4 PCIe cards is that in additional to the signals carried over the PCIe slot they are plugged into they need to send additional signals to the motherboard for which there is no standardized connection set of connections on the PCIe bus.  To get around this limitation, motherboard manufacturers can include a separate Thunderbolt header. which is sometimes labeled as JTBT1 or TBT1 on the motherboard.  The Thunderbolt PCIe card has a corresponding header on it, and comes with a proprietary cable to connect between the card and motherboard. While the additional signals that need to be sent over the Thunderbolt header are somewhat standardized, motherboard manufacturers are also free to implement whatever custom vendor-specific additions like like, like allowing a the system to recognize an on/off button on a Thunderbolt dock they alone offer to power up the system, or recognize what an external peripheral has been plugged in or unplugged from the Thunderbolt port.  Features like this, plus the lack of requirements for standardized features, or even a standard physical layout for the Thunderbolt header, mean that manufacturers can implement what are Thunderbolt PCIe cards that are essentially proprietary in that all features only work with their motherboard and even then only when their custom cable is used between their motherboard and their Thunderbolt PCIe card.  There may be additional cables required in order to route a video card's signals through the Thunderbolt port as well. Because of this, you need to go with the motherboard manufacturer's Thunderbolt PCIe card, unless you want to get a different brand, build a custom cable to connect it to your motherboard, and potentially give up features like hot-plugging devices to it. I believe @Nik Louch identified a card which will work with your motherboard.  You can always double-check with the motherboard manufacturer just to be sure, or find out if there are any issues or limitations to the combination of your motherboard and the card. If you purchase a used Thunderbolt PCIe card, make sure to check with the seller if it comes with all of the cabling necessary to use it, otherwise you may end up having to purchase that separately as well. Regards, Aryeh Goretsky  
    • ChromeOS M137 goes stable, bringing new Face Control policy and more by David Uzondu Google has brought ChromeOS M137 to the stable channel, and it includes a few focused updates for users and IT admins. A key change is a new policy for managing big groups of Chromebooks. The face control accessibility tool, which Google also updated back in ChromeOS M135, now gets a vital control for managers. A new policy called FaceGazeEnabled lets them switch the feature on or off across a whole school or company. The update also brings a new audio feature called crosstalk cancellation. It aims to create a better sound experience using just the Chromebook's built-in speakers. The software processes audio to make it seem like it is surrounding your head, not just coming from two small points. This tries to copy the feel of a surround sound system or good headphones. Any audio gets a boost, but you will notice it most when watching movies or playing games with directional sound. More accessibility tools have arrived, too. ChromeVox now has a direct keyboard shortcut, Search + O + C, that displays spoken text as braille captions on a connected display. For the poor souls in IT, troubleshooting got a little less painful as well. A new event-based log collection system, when enabled by an admin, will automatically upload relevant logs when something specific fails, like an OS crash or a botched update. Instead of digging through mountains of data, administrators get targeted reports sent straight to them. Here's how to enable it: Turn on the Device system log upload setting. Turn on OS update status reporting—For the Report device OS information setting, select OS update status. Turn on device telemetry reporting on crash information—For the Report device telemetry setting, select Crash information. Google also keeps things sane by limiting these targeted uploads to just twice a day per device. As usual, the update is rolling out slowly. If you do not see ChromeOS M137 for your machine yet, just be patient. This phased release lets Google find and address any issues before the update gets to everyone.
    • LG gram Book 15U50T: Is this lightweight laptop the right upgrade for you? by Paul Hill If you’re in the UK looking for a new mid-range laptop that won’t feel underpowered, check out the LG gram Book 15U50T now because it’s at its all-time lowest price on Amazon UK thanks to a 14% discount from its £699.99 RRP. You can get it now for just £599.99 (Buying link at the end). At this price, the laptop definitely makes this mid-range option much more appealing, it’s also pretty new having only come out in January 2025, so you’re definitely getting more value for your money. The delivery is free and will take a few days to arrive unless you take advantage of a Prime member trial and get it next-day in time for Father’s Day. LG gram Book 15U50T: Key features and who it's for The LG gram Book 15U50T features a 15.6-inch Full-HD (1920x1080) anti-glare IPS display, making it ideal for use in well-lit areas as you won’t see yourself staring back. It’s powered by an Intel Core i5 processor (1334U), 16GB of RAM, and has a very fast 512GB NVMe Gen4 SSD. In my opinion, the storage might be a bit tight for some users; however, the device comes with two M.2 slots if you want to upgrade the storage. The LG gram Book 15U50T is ideal for students or professionals who need a device to carry with them out and about. It has an ultra-lightweight design and weighs just 1.65kg - that’s not too far off a similarly sized MacBook Air, but for a fraction of the cost. In terms of ports, there is an HDMI port, two USB-A ports, and two USB-C ports. There's also a 3.5mm headphone jack if you need to plug in headphones. Other noteworthy details about this laptop include that it's running Windows 11 Home with Copilot integration, it has a HD webcam with a privacy shutter, it uses Dolby Atmos audio for immersive sound, and it has a unique feature called gram Link for multi-device (including Android and iOS) connectivity. Should you buy it? If you are a student or a professional that won’t be doing heavy gaming, or using other super intensive applications, this laptop is a solid pick. It’s lightweight - so easy to carry around, it has an anti-reflective screen - so good in well-lit environments; and it features upgradeable storage slots if 512GB is not enough space. On the downside, this laptop has a mid-range processor that could limit your ability to use high-end professional tools. Another thing I’m not really a fan of here is how opaque LG has been with the battery life. As a portable laptop, you’re obviously going to want to take it on the go where you don’t have a charger handy, but all LG says about the battery is that it has a capacity of 51Wh. According to some online sources, variants of this laptop manage about 7 to 10 hours, so if you need a super long battery life, you might be better off with something like a MacBook Air. So should you buy it? If you’re not going to be doing anything super intensive, but can’t stand underpowered and slow budget laptops then this could be the ideal laptop for you. The £100 discount makes it even more appealing! LG gram Book 15U50T: £599.99 (Amazon UK) / RRP £699.99 This Amazon deal is U.K. specific, and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon UK deals page here. Get Prime, Prime Video, Music Unlimited, Audible or Kindle Unlimited, free for the first 30 days As an Amazon Associate we earn from qualifying purchases.
    • Totally different vehicles. Uber has partnered with Waymo for level 5 autonomous vehicles. Waymo has completed 10 million trips and to date, there have been 696 accidents in 4 years and of those 16 of them appear to have been due to an error by the car. In total airbags have only been deployed 38 times. The technology should always be under review and continued to be improved on, but this is a totally different animal to Tesla FSD PS. no I don't work for them etc. I am an analyst for a market intelligence firm and we have a lot of interest from clients looking at the connected car space for advertising etc. so I have studied them
    • Just seems ridiculous that my 2019 imac is no longer getting the latest macOS. Nowadays a 6 year old PC is still a fairly powerful computer. It could easily run the new OS. I also have a 2015 macbook pro with a 4th gen Intel cpu. Its running sequoia (via OCLP) and can still cope not too bad. My imac is way more powerful. Really puts me off ever buying a mac again, with such short support. Open Core legacy again for me then.
  • Recent Achievements

    • Week One Done
      somar86 earned a badge
      Week One Done
    • One Month Later
      somar86 earned a badge
      One Month Later
    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      504
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      186
    4. 4
      +FloatingFatMan
      174
    5. 5
      snowy owl
      132
  • Tell a friend

    Love Neowin? Tell a friend!