• 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

    • In my mind, I might not want to see what they post and the easiest way to do that was to add them to my ignore list.
    • Secure wipe your Windows 11 device with this Data Shredder Stick, now 25% off by Steven Parker Today's highlighted deal comes via our Neowin Deals store, where you can save up to 25% off the Data Shredder Stick. A secure data wiping tool for Windows. The Data Shredder Stick is your ultimate solution for securely erasing sensitive data, ensuring that your information is truly gone and unrecoverable. With its simple drag-and-drop functionality, the Data Shredder Stick allows you to securely wipe individual files or folders with ease. By shredding data, the space it occupied is overwritten, making it impossible to retrieve. This is an essential tool for anyone preparing to sell or dispose of a computer, laptop, or storage drive, giving you peace of mind that your personal or business data won't fall into the wrong hands. Designed for unlimited use, the Data Shredder Stick can be deployed on as many computers and drives as needed. Simply plug the USB drive into your Windows computer, run the app, and start shredding. Whether you're wiping files, folders, or entire drives, this tool makes data security easy, fast, and effective. Protect your privacy with the Data Shredder Stick – the simple, reliable way to ensure your data stays erased for good. Secure data deletion made simple Securely Wipe Hard Drives: When files are deleted from hard drives, they are placed in unallocated space and can be recovered until overwritten. The Data Shredder Stick can wipe all of this deleted space by overwriting every bit of unallocated space on an entire drive ensuring your data is truly gone. Securely Wipe Files or Folders: Simple drag-and-drop operation allows you to wipe files on the fly. When you shred files or folders, the space they occupy is overwritten so no part of the file can be recovered. Shred Your Data Before Selling Equipment: Rest easy whenever you want to sell a computer, laptop, or any type of storage drive Unlimited Uses: Use the Data Shredder Stick on as many computers and drives as you want Data Shredder Stick is simple to use Plug the Data Shredder Stick into your computer and run the app. To shred files or folders, drag-and-drop them into the shredder. To shred all the deleted space from an entire drive, select the drive and shred away Specs: Brand: Paraben Consumer Software Color: red Dimensions: 2" x 0.8" x 0.1" Interface: USB 3.0 Easy plug-and-play Unlimited uses Manufacturer's 1-year warranty Good to know Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop & mobile Updates included Learn more about our Lifetime deals here! The Data Shredder Stick normally costs $39.99 (Amazon), but you can pick this up for just $29.99 for a limited time - that represents a saving of $10 (25% off). For a full description, specifications, and terms, click the link below. Get the Data Shredder Stick for just $29.99 (was $39.99) Ships only to Contiguous US We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • I have two Tab S9 FEs and two Tab A9+ tablets. While the Tab A9+ is not as powerful as the Tab S9 FE, I like the much cheaper Tab A9+ better. It has a slightly more Landscapish display for those who use the Landscape mode. I haven't noticed much difference in the speakers. The S9 FE does better on battery drainage at around 7% an hour vs 9% an hour for the Tab A9+. I don't use Fast Charging because it is not good for the battery and I haven't really compared the charge time between the two. One thing for sure is the Tab A9+ does a lot better at handling memory under Android 15 UI 7 than it did under Android 14, UI 6.1. The Tab A10+ has yet to be released and as I understand it, it has major chipset and charging upgrades. It is expected to be released late this summer or early fall, but with all Samsung hardware releases, I imagine this one will be same where the U.S. is not among the early markets to see a new device.
    • As such, about 30,000 government sector computers would be switching by 2027 or so. I have been there and done it though probably not with as many as 30,000 computers. i worked on a Bank of America conversion project and it was a mess, a complete mess. Computer system conversions are never as easy as they sound in the media or even the Corporate Boardroom or Government high-up offfices. One may ask, what MIcrosoft hardware and sofware the government of Denmark is using in addition to desktop computers and Office?. One thing for sure. We know that they aren't using Windows 10 Mobile.
  • Recent Achievements

    • Explorer
      Case_f went up a rank
      Explorer
    • Conversation Starter
      Jamie Smith earned a badge
      Conversation Starter
    • First Post
      NeoToad777 earned a badge
      First Post
    • Week One Done
      JoeV earned a badge
      Week One Done
    • One Month Later
      VAT Services in UAE earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      549
    2. 2
      ATLien_0
      239
    3. 3
      +Edouard
      160
    4. 4
      +FloatingFatMan
      147
    5. 5
      Michael Scrip
      112
  • Tell a friend

    Love Neowin? Tell a friend!