• 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

    • Generally, Earth never initiated that animals lay straight
    • Several UI improvements masquerading as a major update. I'm truly hating this trend.
    • OpenAI to use Google Cloud despite rivalry, diversifying beyond Microsoft by Paul Hill To help it meet its massive computing demands for training and deploying AI models, OpenAI is looking into a surprising partnership with Google Cloud to use its services. It was widely seen that OpenAI was Google’s biggest threat, but this deal puts an end to the idea that the pair are purely competing. The two companies haven’t made any public announcement about the deal but a source speaking to Reuters claimed that talks had been ongoing for a few months before a deal was finalized in May. Notably, such a deal would see OpenAI expand its compute sources beyond Microsoft Azure. Microsoft had arrangements in place with OpenAI since 2019 that gave it the exclusive right to build new computing infrastructure for the startup. This limitation was loosened earlier this year with the announcement of Project Stargate. OpenAI is now allowed to look elsewhere for compute if Microsoft is unable to meet the demand. A win for Google Cloud, a challenge for Google's AI strategy The deal will see Google Cloud supply computing capacity for OpenAI’s AI model training and inference. This is a big win for Google’s Cloud unit because OpenAI is a massive name in AI and it lends credence to Google’s cloud offering. It also justifies Google Cloud’s expansion of its Tensor Processing Units (TPUs) for external use. On the back of the news, Alphabet’s stock price rose 2.1%, while Microsoft’s sank 0.6%, showing investors think it’s a good move for Google too. While many end users don’t interact with Google Cloud the same way they do with something like Android or Chrome, Cloud is actually a huge part of Google’s business. In 2024, it comprised $43 billion (12%) of Alphabet’s total revenue. With OpenAI as a customer, this figure could rise even more given the massive amounts of compute OpenAI needs. By leveraging Google’s services, it will also give OpenAI access to the search giant’s Tensor Processing Units (TPUs). Unlike GPUs, these chips are specifically designed to handle the kinds of calculations that are most common in AI and machine learning, leading to greater efficiency. Google’s expansion of these chips to external customers has already helped it attract business from Anthropic and Safe Superintelligence. While Google will happily take OpenAI’s money, it needs to tread carefully giving compute power to a rival, which will only make OpenAI more of a threat to Google’s search business. Specifically, it’ll need to manage how resources are allocated between Google’s own AI projects and its cloud customers. Another issue is that Google has been struggling to keep up with the overall demand for cloud computing, even with its own TPUs, according to its Chief Financial Officer in April. By giving access to OpenAI, it means even more pressure. Hopefully, this will be short lived as companies compete to build out capacity to attract customers. OpenAI's push for compute independence Back in 2019 when Microsoft became OpenAI’s exclusive cloud partner in exchange for $1 billion, the AI landscape was much different. End users wouldn’t have access to ChatGPT for another 3 years and the rate of development of new models was less ferocious than it is today. As OpenAI’s compute needs evolve, its relationship with Microsoft has had to evolve too, including this deal with Google and the Stargate infrastructure program. Reuters said that OpenAI’s annualized run rate (the amount they’ll earn in one year at its current pace) had surged to $10 billion, which highlights its explosive growth and need for more resources than Microsoft alone can offer. To make itself more independent, OpenAI has also signed deals worth billions of dollars with CoreWeave, another cloud compute provider, and it is nearing the finalization of the design of its first in-house chip, which could reduce its dependency on external hardware providers altogether. Source: Reuters
    • I don't think that means what you think it means
    • The Google Home app gets video forwarding support and many more features by Aman Kumar Along with releasing the Android 16 update for supported Pixel devices, Google has also showcased a number of features coming to its Home app. First up is PiP, also known as picture-in-picture mode, which will be available for Nest Cams on any Google TV device you own. It’ll be similar to YouTube’s PiP, with which you must be familiar with. A small window will appear in a corner of the TV screen, allowing you to view your Nest Cams without interrupting your viewing experience. The feature is currently in public preview, and you can enroll to try it out before its public release. Another YouTube feature that Google is adding to its Home app is the ability to jump 10 seconds forward or backward in recorded videos. This feature ensures that you don't have to go through the entire footage to locate the moment you’re looking for. Google mentioned in its blog post that it is adding more controls to the Google Home web app. Currently, the web app offers limited functionality, such as setting automations and viewing cameras, but soon you’ll be able to manage more things through it, such as adjusting lighting, controlling temperature, and locking or unlocking the door. Google’s AI model, Gemini, is also getting more controls in the Home app. You can use natural language in the Gemini app to search for specific footage in the camera history. Furthermore, the fallback assistant experience that broadcast commands use is also being updated. You’ll now be able to use your voice to broadcast messages through the connected speakers in your home. The Google blog post also mentions that you are no longer required to use the standalone Nest app to receive smoke and other critical alerts. You can now view the Nest Protect smoke and carbon monoxide (CO) status directly in the Home app. You’ll also be able to run safety checkups and hush alarms through the Home app. In addition to all these features, Google is also making the automation creation process much quicker, will allow you to add more tiles to the Home app Favorites section, and will let you create different Favorites for any other device you use, such as your smartwatch. The Home app will now also support third-party Matter locks. Similar to the Nest x Yale lock, you’ll be able to control various settings of these third-party locks, like managing household access, creating guest profiles, and more.
  • Recent Achievements

    • Week One Done
      Falisha Manpower earned a badge
      Week One Done
    • One Month Later
      elsa777 earned a badge
      One Month Later
    • Week One Done
      elsa777 earned a badge
      Week One Done
    • First Post
      K Dorman earned a badge
      First Post
    • Reacting Well
      rshit earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      543
    2. 2
      ATLien_0
      272
    3. 3
      +FloatingFatMan
      207
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      139
  • Tell a friend

    Love Neowin? Tell a friend!