SlideShare a Scribd company logo
1 of 21
Download to read offline
Dmitri Nesteruk
JetBrains
Managed language = C#, Java, D etc.
GC (garbage collector), Unicode, …
Unmanaged language
Something that compiles to native code
More control, less safety
C/C++, VHDL, etc.
Performance
Stop-the-world GC
Low-level control (e.g., SIMD)
Collections (containers), multithreading
Defense against reverse-engineering
C#, Java are easy to decompile
Hardware support
CUDA, Xeon Phi
Portability (surprise!)
Sudden desire to write everything in С++
Lex the source code
Build AST
Resolve symbols
Traverse the tree, translating it to a different
language
Perfect translation is (of course) impossible
Translate syntax with fidelity
Fill the gaps in what’s missing
Replace equivalent constructs
List<>  vector<>
Handle cases where 1-to-1
mapping is impossible
Integral types
Use types from <cstdint>
int int32_t, byte  uint8_t, etc.
float/double as-is
Extended precision types (System.Decimal)
Need external libs 
Slightly different init rules
Unicode 
Most LoB apps do not absolutely require Unicode (nice to
have)
Relatively safe option:
string  std::wstring
char  wchar_t
Slightly more careless option: string/char
A completely safe solution has to allow strings to be nullptr
I.e., you either use char* or option<string>
Expensive, tedious, just use myString.empty()
Unicode in source (identifiers, literals, …) won’t work
class Person
{
string name;
int age;
}
class Person {
std::string name;
int32_t age;
public:
Person();
};
Managed languages
Give types default values
Allow initialization right in the declaration
In both cases, initialization happens in the
(generated) ctor
In C++, types don’t have default values. So we
are forced to make a constructor ourselves
Property = field+getter+setter
Can be read or write-only
Can be automatic
Name of field not specified
explicitly
Offers no benefit over a field in C++
Can have an inline initializer
More ctor abuse 
Two options here
GetXxx/SetXxx (safe, tedious)
__declspec(property)
(not C++ standard, but nicer)
int age;
public int Age
{
get { return age; }
set { age = value; }
}
// automatic
public int Age
{ get; set; }
__declspec(property(get = GetAge, put = PutAge))
int Age;
int GetAge() const { return age; }
void PutAge(int value) { … }
// later
Person p;
p.Age = 123; // calls PutAge()
Used in many places, e.g.:
Handling UI interactions
Property change notifications
C++ doesn’t have them
Boost.Signals
Tricky since event subscription is done with +=
And unsubscription with −=
template <typename T> class
INotifyPropertyChanged
{
public:
signal<void(const T*, string)>
PropertyChanged;
};
class Player : public INotifyPropertyChanged<Player>
{
int age;
public:
__declspec(property(get = GetAge, put = PutAge)) int Age;
int GetAge() const { return age; }
void PutAge(int value)
{
if (value == age) return;
PropertyChanged(this, "Age"); // oops, a string! (macro?)
age = value;
}
“The big problem”
GC  non-GC translation
Store everything as shared_ptr
Replace every `new` with make_shared
Detecting use-cases for make_unique very
difficult
Circular references (weak_ptr<>?)
References require#includes
Need a list of typeheader for STL etc.
Circular references may need forward
declarations
Header groupings (at namespace or folder
level)
Very tricky internal consistency (topological sort)
Also a good idea for IDEs
Type translation is (relatively) easy
int  int32_t
List<T>  vector<T>
Function call translation is harder
List.Add()  vector.emplace_back(), but…
Value vs ref. stuff
We need two converters
One for .H files
Another for .CPP files (implementation)
The option of doing everything inline isn’t
considered
There are situations where 100% inlining doesn’t
work
Naming convention
Clean Unicode handling
Automated API mapping
Questions?
dn@jetbrains.com
@dnesteruk
Come to the JB booth! (R#C++, CLion)

More Related Content

What's hot

GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
Miller Lee
 
Autovectorization in llvm
Autovectorization in llvmAutovectorization in llvm
Autovectorization in llvm
ChangWoo Min
 

What's hot (20)

Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Q4.11: Using GCC Auto-Vectorizer
Q4.11: Using GCC Auto-VectorizerQ4.11: Using GCC Auto-Vectorizer
Q4.11: Using GCC Auto-Vectorizer
 
Basic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmersBasic c++ 11/14 for python programmers
Basic c++ 11/14 for python programmers
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
 
HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3HKG15-207: Advanced Toolchain Usage Part 3
HKG15-207: Advanced Toolchain Usage Part 3
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Arduino C maXbox web of things slide show
Arduino C maXbox web of things slide showArduino C maXbox web of things slide show
Arduino C maXbox web of things slide show
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
To Swift 2...and Beyond!
To Swift 2...and Beyond!To Swift 2...and Beyond!
To Swift 2...and Beyond!
 
Autovectorization in llvm
Autovectorization in llvmAutovectorization in llvm
Autovectorization in llvm
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Q4.11: NEON Intrinsics
Q4.11: NEON IntrinsicsQ4.11: NEON Intrinsics
Q4.11: NEON Intrinsics
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
maXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps TutorialmaXbox Starter 39 GEO Maps Tutorial
maXbox Starter 39 GEO Maps Tutorial
 
Accelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL GenerationAccelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL Generation
 

Viewers also liked

Использование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработкиИспользование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработки
victor-yastrebov
 

Viewers also liked (14)

Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеТененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
Владислав Шаклеин. Смешивание управляемого и неуправляемого C++ кода в Micros...
 
High quality library from scratch
High quality library from scratchHigh quality library from scratch
High quality library from scratch
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Практика Lock-free. RealTime-сервер
Практика Lock-free. RealTime-серверПрактика Lock-free. RealTime-сервер
Практика Lock-free. RealTime-сервер
 
Асинхронность и сопрограммы
Асинхронность и сопрограммыАсинхронность и сопрограммы
Асинхронность и сопрограммы
 
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxПавел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
Конкурентные ассоциативные контейнеры
Конкурентные ассоциативные контейнерыКонкурентные ассоциативные контейнеры
Конкурентные ассоциативные контейнеры
 
Использование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработкиИспользование юнит-тестов для повышения качества разработки
Использование юнит-тестов для повышения качества разработки
 
Parallel STL
Parallel STLParallel STL
Parallel STL
 
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионаловПолухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
Полухин Антон, Как делать не надо: C++ велосипедостроение для профессионалов
 

Similar to Конверсия управляемых языков в неуправляемые

Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
sarfarazali
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
singhadarsh
 
Tema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdfTema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdf
pepe464163
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
voegtu
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
hmanjarawala
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
voegtu
 

Similar to Конверсия управляемых языков в неуправляемые (20)

Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 
IntroToCSharpcode.ppt
IntroToCSharpcode.pptIntroToCSharpcode.ppt
IntroToCSharpcode.ppt
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Tema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdfTema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdf
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 

More from Platonov Sergey

Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Platonov Sergey
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычислений
Platonov Sergey
 

More from Platonov Sergey (20)

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализация
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практике
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутов
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++
 
C++ exceptions
C++ exceptionsC++ exceptions
C++ exceptions
 
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычислений
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08
 
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...
 
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияДракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим жить
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансы
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузера
 
Concepts lite
Concepts liteConcepts lite
Concepts lite
 
Денис Кормалев Метаобъектная система Qt
Денис Кормалев Метаобъектная система QtДенис Кормалев Метаобъектная система Qt
Денис Кормалев Метаобъектная система Qt
 
Максим Хижинский Lock-free maps
Максим Хижинский Lock-free mapsМаксим Хижинский Lock-free maps
Максим Хижинский Lock-free maps
 

Конверсия управляемых языков в неуправляемые

  • 2. Managed language = C#, Java, D etc. GC (garbage collector), Unicode, … Unmanaged language Something that compiles to native code More control, less safety C/C++, VHDL, etc.
  • 3. Performance Stop-the-world GC Low-level control (e.g., SIMD) Collections (containers), multithreading Defense against reverse-engineering C#, Java are easy to decompile Hardware support CUDA, Xeon Phi Portability (surprise!) Sudden desire to write everything in С++
  • 4. Lex the source code Build AST Resolve symbols Traverse the tree, translating it to a different language Perfect translation is (of course) impossible
  • 5. Translate syntax with fidelity Fill the gaps in what’s missing Replace equivalent constructs List<>  vector<> Handle cases where 1-to-1 mapping is impossible
  • 6. Integral types Use types from <cstdint> int int32_t, byte  uint8_t, etc. float/double as-is Extended precision types (System.Decimal) Need external libs  Slightly different init rules
  • 7. Unicode  Most LoB apps do not absolutely require Unicode (nice to have) Relatively safe option: string  std::wstring char  wchar_t Slightly more careless option: string/char A completely safe solution has to allow strings to be nullptr I.e., you either use char* or option<string> Expensive, tedious, just use myString.empty() Unicode in source (identifiers, literals, …) won’t work
  • 8. class Person { string name; int age; } class Person { std::string name; int32_t age; public: Person(); };
  • 9. Managed languages Give types default values Allow initialization right in the declaration In both cases, initialization happens in the (generated) ctor In C++, types don’t have default values. So we are forced to make a constructor ourselves
  • 10. Property = field+getter+setter Can be read or write-only Can be automatic Name of field not specified explicitly Offers no benefit over a field in C++ Can have an inline initializer More ctor abuse  Two options here GetXxx/SetXxx (safe, tedious) __declspec(property) (not C++ standard, but nicer) int age; public int Age { get { return age; } set { age = value; } } // automatic public int Age { get; set; }
  • 11. __declspec(property(get = GetAge, put = PutAge)) int Age; int GetAge() const { return age; } void PutAge(int value) { … } // later Person p; p.Age = 123; // calls PutAge()
  • 12. Used in many places, e.g.: Handling UI interactions Property change notifications C++ doesn’t have them Boost.Signals Tricky since event subscription is done with += And unsubscription with −=
  • 13. template <typename T> class INotifyPropertyChanged { public: signal<void(const T*, string)> PropertyChanged; };
  • 14. class Player : public INotifyPropertyChanged<Player> { int age; public: __declspec(property(get = GetAge, put = PutAge)) int Age; int GetAge() const { return age; } void PutAge(int value) { if (value == age) return; PropertyChanged(this, "Age"); // oops, a string! (macro?) age = value; }
  • 15. “The big problem” GC  non-GC translation Store everything as shared_ptr Replace every `new` with make_shared Detecting use-cases for make_unique very difficult Circular references (weak_ptr<>?)
  • 16. References require#includes Need a list of typeheader for STL etc. Circular references may need forward declarations Header groupings (at namespace or folder level) Very tricky internal consistency (topological sort) Also a good idea for IDEs
  • 17. Type translation is (relatively) easy int  int32_t List<T>  vector<T> Function call translation is harder List.Add()  vector.emplace_back(), but… Value vs ref. stuff
  • 18. We need two converters One for .H files Another for .CPP files (implementation) The option of doing everything inline isn’t considered There are situations where 100% inlining doesn’t work
  • 19.
  • 20. Naming convention Clean Unicode handling Automated API mapping