<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joey Morrow on Medium]]></title>
        <description><![CDATA[Stories by Joey Morrow on Medium]]></description>
        <link>https://medium.com/@joey.morrow3?source=rss-a80bb2736ace------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TyMpmAuEjiR7AMZUrBcH9A.jpeg</url>
            <title>Stories by Joey Morrow on Medium</title>
            <link>https://medium.com/@joey.morrow3?source=rss-a80bb2736ace------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:45:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joey.morrow3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Build a Distributable Fedora Custom Kernel on Fedora]]></title>
            <link>https://medium.com/@joey.morrow3/how-to-build-a-distributable-fedora-custom-kernel-on-fedora-59b18bced249?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/59b18bced249</guid>
            <category><![CDATA[custom-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[fedora]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Fri, 24 May 2019 17:08:38 GMT</pubDate>
            <atom:updated>2019-05-24T17:08:38.011Z</atom:updated>
            <content:encoded><![CDATA[<p>If you find yourself needing to build a distributable Custom Kernel for Fedora, you’ve found the place! Two reasons I can think of for why you might need to build and know how to apply a Fedora Custom Kernel are as follows:</p><ul><li>Your Target platform doesn’t have enough disk space to build the kernel (~20–30+ GB)</li><li>You need to apply a kernel patch to a bunch of machines (custom IT support)</li></ul><p>For me, I fell into the former case.</p><p>If you’re looking for how to do this on <strong>Fedora IoT</strong>, please go <a href="https://link.medium.com/hW8Ls3WOVW">here</a> instead.</p><p><strong>Requirement</strong>: Your Target and Build platforms should use the same architecture. (Both of my platforms utilize “x86_64” architecture which means these platforms use Intel CPUs.) (You may be able to do some tricky stuff to cross-compile across architectures, but good luck! :P)</p><p>This article is split up into 7 steps. (2hr30min of your computer’s time &amp; 35min of your time)<br>1. <strong>Discovery (~15–20 min)</strong><br>2. <strong>Retrieval (~5 min)<br></strong>3. <strong>Unpack (~3 min)<br></strong>4. <strong>Setup (~3 min)<br></strong>5. <strong>Customizations (~1+ min) <br></strong>6. <strong>Build (~2 hours)</strong><br>7. <strong>Install (~5 min)</strong></p><p>Only steps 1 &amp; 7 are done on the Fedora Target system. Everything else is done on the Fedora Build system.</p><h3>1. Discovery (Run on Target system.)</h3><p>Figure out what we need to figure out- Namely, what kernel version are we downloading? If you already know, you can skip down to section “Retrieval.”</p><p>a. Download Fedora to your platform. Follow directions found at <a href="https://getfedora.org/">https://getfedora.org/</a>. We will be upgrading the stable version of the kernel to our custom kernel, rather than doing a fresh install. So this requires you to install Fedora first. Come back here once your Fedora installation is up.<br>b. Create your user account on the Target platform.<br>c. Run: “dnf update”. (This will ensure your kernel is at the latest stable version.)<br>d. Run: “systemctl reboot”<br>e. Once Fedora system reboots, run: “uname -r”<br>(Mine was “5.0.16–200.fc29.x86_64”.)<br>(Disambiguation: “&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;” ==&gt; Version=5.0.16, Release=200.fc29, Architecture=x86_64)</p><p>This is the kernel version you’re targeting.</p><h3>2. Retrieval (Run on Fedora Build system.)</h3><p>Now that you know the version of the kernel you want to build, you can retrieve it! Fedora publishes the source code!</p><p>a. dnf download --source kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;<br>(Mine was “dnf download kernel-5.0.16–200.fc29.x86_64”.)<br>(If your Build system and Target systems have the same value for the command “uname -r” you may use “dnf download --source kernel-$(uname -r)”.)</p><p>Notice: This downloads a *.rpm file to the current directory. If you want to download this rpm file to a specific location, either ‘cd’ to that directory or read up on the “dnf download” command to figure out where to direct the download output of this command.</p><h3>3. Unpack (Run on Fedora Build system.)</h3><p>Now that you have the Kernel Source, you can unpack it for the ‘rpmbuild; utility to build. The last command unpacks the *.src.rpm file into ~/rpmbuild/*. (Notice you may have multiple rpm packages unpacked at this location. In this case, please be sure to recognize the files you’re touching if you have more than one rpmbuild or kernel you’ve built.)</p><blockquote>$ useradd mockbuild</blockquote><blockquote>$ groupadd mock</blockquote><blockquote>$ rpm -Uvh kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.src.rpm</blockquote><blockquote>(For me it was “rpm -Uvh kernel-5.0.16–200.fc29.src.rpm”)</blockquote><h3>4. Setup (Run on Fedora Build system.)</h3><p>Now that you have all the contents to build the kernel, you need to make sure your Fedora system is capable of building the kernel. You will need to install the following components.</p><blockquote>$ sudo dnf install rpmdevtools ncurses-devel</blockquote><blockquote>$ rpmdev-setuptree</blockquote><blockquote>At directory ~/rpmbuild/SPECS/ you will need issue the following command:<br>$ sudo dnf builddep kernel.spec</blockquote><h3>5. Customizations (Run on Fedora Build system.)</h3><p>Before you build it’s best to make at least one suggested change. This is where you make any changes to the Sources. (Sources and Configurations are found in ~/rpmbuild/SOURCES.)</p><ol><li>Modify the “baserelease” value in &lt;kernel-&lt;<strong>Version</strong>&gt;–&lt;<strong>Release</strong>&gt;.src&gt;/kernel.spec to something higher than 300.<br>Note: Fedora’s Official Build System apparently uses values “100”, “200”, and “300” already. It’s suggested to change this value, but you could choose to change other versioning information instead. If you don’t make any name or versioning changes the Fedora Target system will reject this kernel as it thinks the kernel is already installed. I chose to change the value to “700” arbitrarily.</li><li>This is also where you would make any changes to kernel build flags. You will want to modify the flags found in “kernel-&lt;<strong>Architecture</strong>&gt;.config.”<br>(For me, I modified “kernel-x86_64.config.”)</li></ol><h3>6. Build (Run on Fedora Build system.)</h3><p>Now that your build environment and customizations are ready to go, you can build the kernel! (Notice: I issue these commands from ~/rpmbuild/SPECS directory.)</p><blockquote>$ rpmbuild -bs --target x86_64 --nodeps kernel.spec</blockquote><blockquote>$ rpmbuild -bb --target x86_64 --nodeps kernel.spec</blockquote><p>Notice: This build will take ~2 hours on latest generation Intel Core I7 4 core CPU from the second command “-bb” above.<br>Notice: The build output is now located at $HOME/rpmbuild/*.</p><p><strong>Copy the contents of “$HOME/rpmbuild/RPMS/*” to a flashdrive. </strong>Alternatively, you can use your favorite file sharing technique (eg. scp). This is just what I did. (Notice you may have multiple rpm packages unpacked at this location. In this case, please be sure to recognize the files you’re copying if you have more than one rpmbuild or kernel you’ve built.)</p><p>You can issue the commands with the time utility to see how long the build took by prepending “time” to your command like “$ time rpmbuild …”. The resulting time will be printed after the build completes.</p><h3>7. Install (Run on Fedora Target system.)</h3><p>Now copy the RPMs you copied on the flash drive to the Fedora Target system.</p><p>Now issue the following commands at the location you pasted to:</p><blockquote>$ dnf install ./kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-core-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-modules-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-modules-extra-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm<br>(I did: $ dnf install ./kernel-*)</blockquote><blockquote>$ systemctl reboot</blockquote><p>If you run into an error at boot stating something along the lines of “vmlinuz has invalid signature,” you will need to disable Secure Boot in your system’s BIOS and then restart your system for the time-being. I am currently troubleshooting how to sign the custom kernel and upload the keys into the BIOS to validate your custom kernel for use.</p><blockquote>$ uname -r</blockquote><p>The output of “uname -r” should match your custom built kernel! Have fun! :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59b18bced249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build Fedora IoT Custom Kernel on Fedora]]></title>
            <link>https://medium.com/@joey.morrow3/how-to-build-fedora-iot-custom-kernel-on-fedora-fe5219b97e56?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5219b97e56</guid>
            <category><![CDATA[fedora-iot]]></category>
            <category><![CDATA[custom-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Wed, 03 Apr 2019 20:17:42 GMT</pubDate>
            <atom:updated>2019-05-24T17:10:55.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lq3mboEdOh7MxDREq8r3ng.jpeg" /><figcaption>Pretty Pretty Picture to Catch Eyes! :D</figcaption></figure><h3>How To Build a Distributable Fedora IoT Custom Kernel on Fedora</h3><p>We often find ourselves deploying Fedora IoT on less powerful machines and generally have a Fedora development machine. This evokes a need for cross compiling the Fedora IoT on a Fedora machine to save on build time. This article describes what you need to do to build a custom Fedora IoT kernel on a Fedora machine and then how to install that custom kernel on the Fedora IoT machine.</p><p>If you’re looking for how to do this on <strong>Fedora WS or Server</strong>, please go <a href="https://link.medium.com/nYLQBh6kXW">here</a> instead.</p><p>Requirement: Your Fedora IoT and Fedora platforms should use the same architecture. (Both of my platforms utilize “x86_64” architecture which means these platforms use Intel CPUs.) (You may be able to do some tricky stuff to cross-compile across architectures, but good luck! :P)</p><p>This article is split up into 7 steps. (2hr30min of your computer’s time &amp; 35min of your time)<br>1. <strong>Discovery (~15–20 min)</strong><br>2. <strong>Retrieval (~5 min)<br></strong>3. <strong>Unpack (~3 min)<br></strong>4. <strong>Setup (~3 min)<br></strong>5. <strong>Customizations (~1+ min) <br></strong>6. <strong>Build (~2 hours)</strong><br>7. <strong>Install (~5 min)</strong></p><p>Only steps 1 &amp; 7 are done on the Fedora IoT system. Everything else is done on the Fedora system.</p><h3>1. Discovery (Run on Fedora IoT system.)</h3><p>Figure out what we need to figure out- Namely, what kernel version are we downloading? If you already know, you can skip down to section “Retrieval.”</p><p>a. Download Fedora IoT to your platform. Follow directions found at <a href="https://iot.fedoraproject.org/">https://iot.fedoraproject.org/</a>. We will be upgrading the stable version of the kernel to our custom kernel, rather than doing a fresh install. So this requires you to install Fedora IoT first.<br>b. Create your user account on the Fedora IoT platform.<br>c. Run: “rpm-ostree update”. (This will ensure your kernel is at the latest stable version.)<br>d. Run: “systemctl reboot”<br>e. Once Fedora IoT system reboots, run: “uname -r”<br>(Mine was “4.20.16–200.fc29.x86_64”.)<br>(Disambiguation: “&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;” ==&gt; Version=4.20.16, Release=200.fc29, Architecture=x86_64)</p><p>This is the kernel version you’re targeting.</p><h3>2. Retrieval (Run on Fedora system.)</h3><p>Now that you know the version of the kernel you want to build, you can retrieve it! Fedora IoT publishes the source code!</p><p>a. Go to the following dashboard for Fedora IoT’s official build system to find your specific kernel package at <a href="https://koji.fedoraproject.org/koji/packageinfo?packageID=8">https://koji.fedoraproject.org/koji/packageinfo?packageID=8</a> as “kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;”.<br>b. Click on your “kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;” link.<br>c. Find and download your matching “kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.src.rpm” package.<br>(Mine was “kernel-4.20.16–200.fc29.src.rpm”.)</p><h3>3. Unpack (Run on Fedora system.)</h3><p>Now that you have the Kernel Source, you can unpack it!</p><p>The first command just creates a place to plop the output. The second command plops the output!</p><blockquote>$ mkdir kernel-4.20.16–200.fc29.src</blockquote><blockquote>$ cd kernel-4.20.16–200.fc29.src &amp;&amp; rpm2cpio ../kernel-4.20.16–200.fc29.src.rpm | cpio -idmv</blockquote><h3>4. Setup (Run on Fedora system.)</h3><p>Now that you have all the contents to build the kernel, you need to make sure your Fedora system is capable of building the kernel. You will need to install the following components.</p><blockquote>$ sudo dnf install bison rpmdevtools flex python3</blockquote><blockquote>$ sudo dnf install fedpkg fedora-packager ncurses-devel pesign</blockquote><blockquote>At &lt;kernel-4.20.16–200.fc29.src&gt; you will need issue the following command:<br>$ sudo dnf builddep kernel.spec</blockquote><h3><strong>5. Customizations </strong>(Run on Fedora system.)</h3><p>Before you build it’s best to make at least one suggested change.</p><ol><li>Modify the “baserelease” value in &lt;kernel-4.20.16–200.fc29.src&gt;/kernel.spec to something higher than 300.<br>Note: Fedora Build System apparently uses values “100”, “200”, and “300” already. It’s suggested to change this value, but you could choose to change other versioning information instead. If you don’t make any name or versioning changes the Fedora IoT system will reject this kernel as it thinks the kernel is already installed.</li><li>This is also where you would make any changes to kernel build flags. You will want to modify the flags found in “kernel-&lt;<strong>Architecture</strong>&gt;.config.”<br>(For me, I modified “kernel-x86_64.config.”)</li></ol><h3><strong>6. Build </strong>(Run on Fedora system.)</h3><p>Now that your build environment and customizations are ready to go, you can build the kernel!</p><blockquote>$ rpmbuild -bs --target x86_64 --nodeps kernel.spec --define “_sourcedir $PWD”</blockquote><blockquote>$ rpmbuild -bb --target x86_64 --nodeps kernel.spec --define “_sourcedir $PWD”</blockquote><p>Notice: This build will take ~2 hours on latest generation Intel Core I7 4 core CPU from the second command “-bb” above.<br>Notice: The build output is now located at $HOME/rpmbuild/*.</p><p>Copy the contents of “$HOME/rpmbuild/RPMS/*” to a flashdrive. Alternatively, you can use your favorite file sharing technique (eg. scp). This is just what I did.</p><p>You can issue the commands with the time utility to see how long the build took by prepending “time” to your command like “$ time rpmbuild …”. The resulting time will be printed after the build completes.</p><h3><strong>7. Install (Run on Fedora IoT system.)</strong></h3><p>Now copy the RPMs you copied on the flash drive to the Fedora IoT system.</p><p>Now issue the following commands at the location you pasted to:</p><blockquote>$ rpm-ostree override replace ./kernel-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-core-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-modules-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm ./kernel-modules-extra-&lt;<strong>Version</strong>&gt;-&lt;<strong>Release</strong>&gt;.&lt;<strong>Architecture</strong>&gt;.rpm<br>(I did: $ rpm-ostree override replace ./kernel-4.20.16–700.fc29.x86_64.rpm ./kernel-core-4.20.16–700.fc29.x86_64.rpm ./kernel-modules-4.20.16–700.fc29.x86_64.rpm ./kernel-modules-extra-4.20.16–700.fc29.x86_64.rpm)</blockquote><blockquote>$ systemctl reboot</blockquote><p>If you run into an error at boot stating something along the lines of “vmlinuz has invalid signature,” you will need to disable Secure Boot in your system’s BIOS and then restart your system for the time-being. I am currently troubleshooting how to sign the custom kernel and upload the keys into the BIOS to validate your custom kernel for use.</p><blockquote>$ uname -r</blockquote><p>The output of “uname -r” should match your custom built kernel! Have fun! :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5219b97e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why we need a Cancel Trigger for Amazon Echo and Google Home]]></title>
            <link>https://medium.com/@joey.morrow3/why-we-need-a-cancel-trigger-for-amazon-echo-and-google-home-e431e133a95b?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/e431e133a95b</guid>
            <category><![CDATA[amazon-echo]]></category>
            <category><![CDATA[google-home]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Thu, 26 Jul 2018 20:27:44 GMT</pubDate>
            <atom:updated>2018-07-26T20:30:37.673Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever talked to your smart home assistant to find it hasn’t understood you correctly? While this is happening, you have to cease your train of thought to yell, “Alexa, Stop!” or “Ok Google, Cancel!”. (Sometimes “Shut up!” works.)</p><p>This is terribly bad for your general mood. You’ve been rudely interrupted expecting this technology to work as expected. Here’s the truth: This stuff may never work 100% of the time.</p><p>We need a quicker way to return to our train of thought. Think of “Alexa” spelled backward: “<strong>Axela</strong>”</p><p>Imagine, “Alexa, Turn on the Living Room Lights” and her response is “I’m sorry, I don’t understand the command.” In the three seconds it took her to say this, you could have stated “<strong>Axela!</strong>” (as though it’s a magic word). This would have stopped Alexa in her tracks.</p><p>Music. Imagine instead of saying “Alexa, stop,” you could just say “Axela.”</p><p>Imagine a world where we’re not talking to our smart home assistants like misbehaving children. Imagine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e431e133a95b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Equivalent to C++ std::bind Args]]></title>
            <link>https://medium.com/@joey.morrow3/c-equivalent-to-c-std-bind-args-bb47650777e4?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb47650777e4</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 05:30:29 GMT</pubDate>
            <atom:updated>2017-10-18T05:30:29.249Z</atom:updated>
            <content:encoded><![CDATA[<p>In C++ you would do things as follows (<a href="http://cpp.sh/4s5w">http://cpp.sh/4s5w</a>):</p><pre>// C++ Headers because most blogs forget!<br>#include &lt;iostream&gt; // For std::cout, &lt;&lt;, and std::endl<br>#include &lt;string&gt; // For std::string<br>#include &lt;functional&gt; // For std::function &amp; std::bind</pre><p>In C++, when you want to register a callback function your simply use std::bind as follows at add your own additional callback params (NOTICE: ‘42’):</p><pre>typedef std::function&lt;void(std::string)&gt; MyCallbackType;</pre><pre>static void MyCallback_Impl(std::string str, int extraParam)<br>{<br>    std::cout &lt;&lt; &quot;String: &quot; &lt;&lt; str &lt;&lt; &quot; and Integer: &quot; &lt;&lt; extraParam &lt;&lt; std::endl;<br>}</pre><pre>int main()<br>{<br>  MyCallbackType mct = std::bind(&amp;MyCallback_Impl, std::placeholders::_1, 42);<br>  <br>  mct(&quot;\&quot;Hello World!\&quot;&quot;);<br>  <br>  return 0;<br>}</pre><p>So, in C#, how would we append the answer to the universe, life, and everything (ahem, the integer value ‘42’)? We would use a Lambda to implement our Delegate! See (<a href="http://rextester.com/IGHK12370">http://rextester.com/IGHK12370</a>):</p><pre>//C# Includes<br>using System;</pre><p>Here’s the source:</p><pre>public class Program<br>{<br>    public delegate void MyDelegateType(String str);<br>    <br>    static void MyDelegateImplEquivalentToCPPCallbackImpl(String str, int extraParam)<br>    {<br>        Console.WriteLine(&quot;String: &quot; + str + &quot; and Integer: &quot; + extraParam);<br>    }<br>    <br>    public static void Main(string[] args)<br>    {<br>        int my_int = 42;<br>        <br>        MyDelegateType mdt = (_1) =&gt; { MyDelegateImplEquivalentToCPPCallbackImpl(_1, my_int); };<br>    <br>        mdt(&quot;\&quot;Hello World!\&quot;&quot;);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb47650777e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert C++ Asynchronous functions to Synchronous functions]]></title>
            <link>https://medium.com/@joey.morrow3/how-to-convert-c-asynchronous-functions-to-synchronous-functions-bba9489bed71?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba9489bed71</guid>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Fri, 13 Oct 2017 23:13:53 GMT</pubDate>
            <atom:updated>2017-10-13T23:13:53.700Z</atom:updated>
            <content:encoded><![CDATA[<p>How to convert C++ Async functions to Sync functions:</p><pre>#include &lt;functional&gt; //std::function<br>#include &lt;thread&gt; //std::thread (to invoke callback later.. ie. 3 seconds)<br>#include &lt;future&gt; // std::future &amp; std::promise<br>#include &lt;iostream&gt; // std::cout &amp; std::endl &amp; &lt;&lt;<br>#include &lt;string&gt; // std::string<br>#include &lt;chrono&gt; // sleep</pre><pre>typedef std::function &lt;void(const std::string)&gt; ReturnHandler;</pre><pre>//===============================<br>// Implmentations</pre><pre>void Imp_ReturnHandler(const std::string value, std::promise&lt;std::string&gt;&amp; prom)<br>{<br>    std::string newValue = &quot;NEW: &quot;;<br>    newValue.append(value);</pre><pre>prom.set_value(newValue);<br>}</pre><pre>/**<br> * Spins off thread to go out and asynchronously get the value.<br> */<br>bool GetAsync(ReturnHandler returnHandler)<br>{<br>    std::thread([returnHandler] {<br>            std::this_thread::sleep_for(std::chrono::milliseconds(3000));<br>            returnHandler(&quot;This is the response!&quot;);<br>        }).detach();<br>    return true;<br>}</pre><pre>/**<br> * Awaits and returns response synchronously.<br> */<br>bool GetSync(std::string&amp; response, const int timeout)<br>{<br> std::promise&lt;std::string&gt; prom;<br> <br> bool err = GetAsync(std::bind(&amp;Imp_ReturnHandler, std::placeholders::_1, std::ref(prom)));<br> <br> if(!err)<br> {<br>     std::cout &lt;&lt; &quot;Failure: Failed to perform GetAsync()!&quot; &lt;&lt; std::endl;<br>     return false;<br> }<br> <br> std::future&lt;std::string&gt; fut = prom.get_future();</pre><pre>response = fut.get();<br> <br> return true;<br>}</pre><pre>int main()<br>{<br>    std::string response;<br>    bool err = GetSync(response, 0);<br>    if (!err)<br>    {<br>        std::cout &lt;&lt; &quot;Failure: Failed to perform GetSync()!&quot; &lt;&lt; std::endl;<br>        return -1;<br>    }<br>    std::cout &lt;&lt; &quot;Received response: &quot; &lt;&lt; response &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p><a href="http://cpp.sh/36ok">C++ Shell</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba9489bed71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to map Unmanaged C++ Member Callback Functions to C# Member Delegates]]></title>
            <link>https://medium.com/@joey.morrow3/how-to-map-unmanaged-c-member-callback-functions-to-c-member-delegates-b7ee798f5efc?source=rss-a80bb2736ace------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ee798f5efc</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[managed-cplusplus]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[unmanaged-cplusplus]]></category>
            <dc:creator><![CDATA[Joey Morrow]]></dc:creator>
            <pubDate>Thu, 05 Oct 2017 15:15:38 GMT</pubDate>
            <atom:updated>2017-10-05T15:16:34.189Z</atom:updated>
            <content:encoded><![CDATA[<p>I am creating this blog post because I didn’t find any *good* generic samples of this already. I am very surprised MSDN wasn’t more straightforward with this stuff.</p><p>This post will illustrate how you can invoke a C# Member Delegate Function from an Unmanaged C++ Library (DLL) as a C++ std::function callback. Maps C++ Member Function Pointer to a C# Member Delegate Function.</p><p>Note: If you haven’t picked up on it yet, “Delegate Function” is what the C# world calls their C/C++ Function Pointer equivalent.</p><p>There will be four components to this:<br>1. <strong>C# App</strong> (*.exe) that will register a Delegate with a Managed C++ Library<br>2. A <strong>Managed C++ Library</strong> (Only the public interface is fully managed.)<br>Note: Only the Public interface to the C++ Library is required to be Managed. Private members, functions, and source code below declarations can be Unmanaged. I think this is a point most people don’t realize.<br>2a. A single <strong>Unmanaged C++ static function</strong> to be registered as the std::function callback to a fully Unmanaged C++ Library.<br>4. A sample <strong>Unmanaged C++ Library </strong>interface (ie. Header only).</p><h3><strong>C# App</strong> (.exe)</h3><p>With a Delegate function “MyCSClass. MyCSUpdateOccurredCB” we want to register as a callback:</p><p>Note: Simply add the Managed C++ Library Project as a Reference for this C# Project in Visual Studio.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;</pre><pre>namespace CS_SampleApp<br>{<br>    public class MyCSClass<br>    {<br>        // Function to be used a Delegate.<br>        public int MyCSUpdateOccurredCB(int num, string json)<br>        {<br>            return 0;<br>        }<br>    }</pre><pre>class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            // Create an instantiation of MyCSClass<br>            MyCSClass myCSClass = new MyCSClass();</pre><pre>            // Obtain a reference to the Member Delegate.<br>            CPP_Managed_UpdateOccurred cb = new CPP_Managed_UpdateOccurred(myCSClass.MyCSUpdateOccurredCB);</pre><pre>            // Instantiate and create a reference to a Managed C++ Object that converts Delegates to std::function callbacks.<br>            MyCPPManagedClass myCPPclass = new MyCPPManagedClass();</pre><pre>            // Register delegate in Managed C++ layer.<br>            myCPPclass.SetUpdateOccurredCB(cb);</pre><pre>            // Load some file as a System.String (AKA &quot;System::String^&quot; in Managed C++.<br>            // First, load file in a StreamReader object.<br>            System.IO.StreamReader din = System.IO.File.OpenText(&quot;some_sample.json&quot;);<br>            // Lastly, convert StreamReader to System.String.<br>            myCPPclass.Setup(din.ReadToEnd());<br>        }<br>    }<br>}</pre><h3>Managed C++ Library (DLL) with Unmanaged C++ components:</h3><p>Note: Simply configure this project as a C++ Console App. Once Visual Studio project is created, modify properties to make it be a .dll (by default it’s a .exe). Add a reference to the Unmanaged C++ Library project below.</p><p>Managed C++ Library Header (MyCPPClass.h):</p><pre>#pragma once</pre><pre>// <strong>Unmanaged declarations</strong>:<br>#include &quot;MyUnmanagedCPPLibrary.h&quot;</pre><pre>// Unmanaged C++ Function Declaration<br>void MyUnmanagedCPPUpdateOccurredCB(my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType updateType, std::string json, void* callbackParam); // Take notice of this &#39;void*&#39;. It&#39;s useful later. ;)</pre><pre>// <strong>Managed declarations</strong>:</pre><pre>public delegate int CS_UpdateOccurredCB(CS_UpdateType, System::String^ json); // Notice, this Managed C++ Delegate Function type declaration is equivalent to a &quot;std::function&quot; </pre><pre>public enum class CS_UpdateType {<br>    FinishedParsingInputJSON, // This is an update telling you your input JSON has been successfully parsed. Input JSON is unchanged and sent back through the delegate function.<br>    CreatedNewJSON, // eg. This could theoretically be from a remote client<br>    SomeOtherUpdate, // Just here for example. All of these are just for example, really.<br>    Unknown<br>};</pre><pre>public ref class MyCPPManagedClass sealed<br>{<br>    public: // Constructor<br>        MyCPPManagedClass();<br>    public: // C# Callback Implementation<br>        int MyCSUpdateOccurredCB(CS_UpdateType updateType, System::String^ json);<br>    public: // C# Callback (ie. Delegate) Setter<br>        void SetUpdateOccurredCB(CS_UpdateOccurredCB^ callback);<br>    public: // Provide similar API that Unmanaged C++ DLL does.<br>        void Setup(System::String^ json);</pre><pre>private:<br>        CS_UpdateOccurredCB^ m_updateOccurredCB;<br>        my::unmanaged::class::MyUnmanagedCPPLibrary* m_unmanagedLibrary;<br>};</pre><p>Managed C++ Library Source (MyCPPClass.cpp):</p><pre>#include &quot;SHA_CPP_Consumer_Managed.h&quot;<br>#include &lt;fstream&gt;</pre><pre>// Have to provide an explicit mapping utility between the Unmanaged UpdateType and the Managed (equivalent to C#) UpdateType to prevent any possible mismatch. (The Unmanaged enum values won&#39;t be auto-magically available in your C# app. The Managed enum values will.)</pre><pre>CS_UpdateType ConvertCPPUpdateTypeToCSUpdateType(my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType updateType)<br>{</pre><pre>switch (updateType)<br>    {<br>        case my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType::FinishedParsingInputJSON:<br>            return CS_UpdateType::FinishedParsingInputJSON;<br>            break;<br>        case my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType::CreatedNewJSON:<br>            return CS_UpdateType::CreatedNewJSON;<br>            break;<br>        case my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType::SomeOtherUpdate:<br>            return CS_UpdateType::SomeOtherUpdate;<br>            break;<br>        default:<br>            return CS_UpdateType::Unknown;<br>            break;<br>    }<br>}</pre><pre>// Provided a std::string -&gt; System::String^ helper function.<br>System::String^ ConvertCPPStringToCSString(std::string cpp_string)<br>{<br>    return gcnew System::String(cpp_string.c_str());<br>}</pre><pre>// Provided a System::String^ -&gt; std::string helper function.<br>#include &lt;msclr\marshal_cppstd.h&gt;<br>std::string ConvertCSStringToCPPString(System::String^ cs_string)<br>{<br>    msclr::interop::marshal_context context;<br>    return context.marshal_as&lt;std::string&gt;(cs_string);<br>}</pre><pre>MyCPPManagedClass::MyCPPManagedClass()<br>{<br>    // Initialize member variables.<br>    m_updateOccurredCB = nullptr;<br>    m_unmanagedLibrary = new my::unmanaged::class::MyUnmanagedCPPLibrary();<br>}</pre><pre>void MyCPPManagedClass::SetUpdateOccurredCB(CS_UpdateOccurredCB ^ callback)<br>{<br>    // Convert C# Function Delegate to C-style pointer.<br>    System::IntPtr callbackPtr = System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callback);<br>    void* cb = callbackPtr.ToPointer();</pre><pre>// Register static C-style callback to Unmanaged Library (DLL) API.<br>    m_unmanagedLibrary-&gt;SetUpdateOccurredCB(std::bind(MyCPPUpdateOccurredCB, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, cb));<br>}</pre><pre>void MyCPPManagedClass::Setup(System::String ^ json)<br>{<br>    m_unmanagedLibrary-&gt;Setup(ConvertCSStringToCPPString(json));<br>}</pre><pre>// Update from Unmanaged C++ coming in now.<br>void MyCPPUpdateOccurredCB(my::unmanaged::class::MyUnmanagedCPPLibrary::UpdateType updateType, std::string json, void * callbackParam)<br>{<br>    // Convert C-style enum to C#-style enum.<br>    CS_UpdateType cs_updateType = ConvertCPPUpdateTypeToCSUpdateType(updateType);</pre><pre>    // Convert C-style string to C#-style string.<br>    System::String^ cs_json = ConvertCPPStringToCSString(json);</pre><pre>    // At the following link in the second example, they mention you should use GCHandle::Alloc() and store the handle elsewhere than in this function. That will prevent the GarbageCollector from cleaning this up.</pre><pre>    /// https://msdn.microsoft.com/en-us/library/367eeye0.aspx // Needs some research, or you risk getting your Delegate cleaned out from under you.</pre><pre>    // Convert C-style pointer to Delegate Function<br>    CS_UpdateOccurredCB^ cb = (CS_UpdateOccurredCB^)System::Runtime::InteropServices::Marshal::GetDelegateForFunctionPointer(System::IntPtr(callbackParam), CS_UpdateOccurredCB::typeid);</pre><pre>    // Forward this event to the C# Delegate now.<br>    cb(cs_updateType, cs_json);<br>}</pre><h3><strong>Fully Unmanaged C++ Library (DLL)</strong></h3><p>Unmanaged C++ Header (MyUnmanagedCPPLibrary.h) // No source is necessary. Just have a totally unmanaged C++ class and wrap it with the similar managed code as shown above for each callback type (ie. std::function declaration) in this unmanaged header declaring the interface for your DLL.</p><pre>#pragma once</pre><pre>#include &lt;string&gt;<br>#include &lt;functional&gt;</pre><pre>namespace my {<br>namespace unmanaged {<br>namespace class {</pre><pre>class __declspec(dllexport) MyUnmanagedCPPLibrary<br>{<br>    public:<br>        MyUnmanagedCPPLibrary();<br>        ~MyUnmanagedCPPLibrary();</pre><pre>        // Registers a string (encoded as JSON) with the stack.<br>    void Setup(std::string json);</pre><pre>        /**<br>         * The reason an invocation of UpdateOccurredCB could occur.<br>         */<br>        enum UpdateType {<br>            FinishedParsingInputJSON,<br>            CreatedNewJSON,<br>            SomeOtherUpdate,<br>            Unknown<br>        };</pre><pre>          /**<br>          * Applications implement this callback to consume any <br>          * updates to their Input JSON or to be notified the JSON<br>          * has changed.<br>          *<br>          * @param updateType The reason this callback was invoked.<br>          * @param json Any JSON key-value pairs that changed.<br>          */<br>         typedef std::function&lt;void(MyUnmanagedCPPLibrary::UpdateType updateType, std::string json)&gt; UpdateOccurredCB;</pre><pre>        /**<br>         * Register a callback with the stack that will invoke<br>         * the application layer to handle updates to an Item.<br>         */<br>        void SetUpdateOccurredCB(MyUnmanagedCPPLibrary::UpdateOccurredCB callback);</pre><pre>    private:<br>        // internal handle to the registered callback set in &quot;SEtUpdateOccurredCB()&quot; above.<br>        MyUnmanagedCPPLibrary::UpdateOccurredCB m_UpdateOccurredCB;</pre><pre>};<br>} // class::<br>} // unmanaged::<br>} // my::</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ee798f5efc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>